package com.junzhiit.nengji.api.service.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.bainaeco.framework.util.DateUtil;
import com.bainaeco.framework.util.serializer.Format;
import com.junzhiit.nengji.api.rabbitmq.RabbitMQService;
import com.junzhiit.nengji.api.service.CommissionHistoryService;
import com.junzhiit.nengji.api.service.CouponsService;
import com.junzhiit.nengji.api.service.OrdersGoodsService;
import com.junzhiit.nengji.api.service.OrdersService;
import com.junzhiit.nengji.api.service.PostageTemplateService;
import com.junzhiit.nengji.api.service.RebateService;
import com.junzhiit.nengji.api.service.TransactionService;
import com.junzhiit.nengji.api.service.UserCouponsService;
import com.junzhiit.nengji.api.web.exception.GoodsNotFoundException;
import com.junzhiit.nengji.api.web.exception.LogisticsNumberErrorException;
import com.junzhiit.nengji.api.web.exception.MoneyNotMuchException;
import com.junzhiit.nengji.api.web.exception.NotFoundException;
import com.junzhiit.nengji.api.web.exception.OrderNotFoundException;
import com.junzhiit.nengji.api.web.exception.OrdersGoodsNotFoundException;
import com.junzhiit.nengji.api.web.exception.OrdersNotFoundException;
import com.junzhiit.nengji.api.web.exception.SkuContentNotFoundException;
import com.junzhiit.nengji.api.web.exception.UserNotFoundException;
import com.junzhiit.nengji.api.web.exception.UserVipNotFoundException;
import com.junzhiit.nengji.api.web.util.APICodeStatus;
import com.junzhiit.nengji.api.web.util.Constants;
import com.junzhiit.nengji.api.web.util.FileUtil;
import com.junzhiit.nengji.api.web.util.OrderNumberUtils;
import com.junzhiit.nengji.api.web.util.RequestUtil;
import com.junzhiit.nengji.api.web.util.aliyun.AliyunOSSClientUtil;
import com.junzhiit.nengji.api.web.util.aliyun.LogisticsUtil;
import com.junzhiit.nengji.api.web.util.aliyun.bean.LogisticsResultDate;
import com.junzhiit.nengji.api.web.util.rsa.AESUtil;
import com.junzhiit.nengji.api.web.util.rsa.Coder;
import com.junzhiit.nengji.api.web.util.tools.NumberUtils;
import com.junzhiit.nengji.api.web.util.wechat.MessageUtil;
import com.junzhiit.nengji.api.web.util.wechat.TemplateMessageUtil;
import com.junzhiit.nengji.api.web.util.wechat.WeChatUtils;
import com.junzhiit.nengji.api.web.util.wechat.bean.OrderInfo;
import com.junzhiit.nengji.api.web.util.wechat.bean.PayParam;
import com.junzhiit.nengji.api.web.util.wechat.bean.TemplateMessageParam;
import com.junzhiit.nengji.api.web.vo.AddressVO;
import com.junzhiit.nengji.api.web.vo.CouponsDetailsVO;
import com.junzhiit.nengji.api.web.vo.CreateOrderVO;
import com.junzhiit.nengji.api.web.vo.FreightVO;
import com.junzhiit.nengji.api.web.vo.ListVO;
import com.junzhiit.nengji.api.web.vo.OrderInfoGoodsVO;
import com.junzhiit.nengji.api.web.vo.OrderInfoVO;
import com.junzhiit.nengji.api.web.vo.OrdersGoodsVO;
import com.junzhiit.nengji.api.web.vo.OrdersPaySuccessVO;
import com.junzhiit.nengji.api.web.vo.OrdersShopVO;
import com.junzhiit.nengji.api.web.vo.OrdersVO;
import com.junzhiit.nengji.api.web.vo.RebateVO;
import com.junzhiit.nengji.api.web.vo.ResultVO;
import com.junzhiit.nengji.api.web.vo.TransactionAddVO;
import com.junzhiit.nengji.api.web.vo.UserConfigVO;
import com.junzhiit.nengji.api.web.vo.UserFormIdVO;
import com.junzhiit.nengji.bo.CartBO;
import com.junzhiit.nengji.bo.GoodsBO;
import com.junzhiit.nengji.bo.GoodsDetailBO;
import com.junzhiit.nengji.bo.OrdersBO;
import com.junzhiit.nengji.bo.OrdersGoodsBO;
import com.junzhiit.nengji.bo.ShopDetailBO;
import com.junzhiit.nengji.bo.UserBO;
import com.junzhiit.nengji.bo.UserCouponsInfoBO;
import com.junzhiit.nengji.dao.AddressDAO;
import com.junzhiit.nengji.dao.BalanceHistoryDAO;
import com.junzhiit.nengji.dao.CartDAO;
import com.junzhiit.nengji.dao.GoodsDAO;
import com.junzhiit.nengji.dao.GoodsDataHistoryDAO;
import com.junzhiit.nengji.dao.IndustryDAO;
import com.junzhiit.nengji.dao.OrdersDAO;
import com.junzhiit.nengji.dao.OrdersDataHistoryDAO;
import com.junzhiit.nengji.dao.OrdersGoodsDAO;
import com.junzhiit.nengji.dao.PayHistoryDAO;
import com.junzhiit.nengji.dao.RechargeRecordDAO;
import com.junzhiit.nengji.dao.ShopClientDAO;
import com.junzhiit.nengji.dao.ShopDAO;
import com.junzhiit.nengji.dao.ShopsLocatedDAO;
import com.junzhiit.nengji.dao.SkuContentDAO;
import com.junzhiit.nengji.dao.SystemConfigDAO;
import com.junzhiit.nengji.dao.UserConfigDAO;
import com.junzhiit.nengji.dao.UserCouponsDAO;
import com.junzhiit.nengji.dao.UserDAO;
import com.junzhiit.nengji.dao.UserGoodsDAO;
import com.junzhiit.nengji.dao.UserVipDAO;
import com.junzhiit.nengji.dao.VipHistoryDAO;
import com.junzhiit.nengji.dao.cache.UserCacheDAO;
import com.junzhiit.nengji.dao.util.DIYKey;
import com.junzhiit.nengji.model.Address;
import com.junzhiit.nengji.model.BalanceHistory;
import com.junzhiit.nengji.model.Goods;
import com.junzhiit.nengji.model.GoodsDataHistory;
import com.junzhiit.nengji.model.Industry;
import com.junzhiit.nengji.model.Orders;
import com.junzhiit.nengji.model.OrdersDataHistory;
import com.junzhiit.nengji.model.OrdersGoods;
import com.junzhiit.nengji.model.PayHistory;
import com.junzhiit.nengji.model.RebateInfo;
import com.junzhiit.nengji.model.RechargeRecord;
import com.junzhiit.nengji.model.Shop;
import com.junzhiit.nengji.model.ShopClient;
import com.junzhiit.nengji.model.ShopsLocated;
import com.junzhiit.nengji.model.SkuContent;
import com.junzhiit.nengji.model.SystemConfig;
import com.junzhiit.nengji.model.User;
import com.junzhiit.nengji.model.UserConfig;
import com.junzhiit.nengji.model.UserCoupons;
import com.junzhiit.nengji.model.UserGoods;
import com.junzhiit.nengji.model.UserVip;
import com.junzhiit.nengji.model.VipHistory;
import com.junzhiit.nengji.model.enums.BalanceHistoryOperation;
import com.junzhiit.nengji.model.enums.BalanceHistoryStatus;
import com.junzhiit.nengji.model.enums.ConfirmType;
import com.junzhiit.nengji.model.enums.CouponFullSubtraction;
import com.junzhiit.nengji.model.enums.CouponsPlatform;
import com.junzhiit.nengji.model.enums.CouponsType;
import com.junzhiit.nengji.model.enums.Is;
import com.junzhiit.nengji.model.enums.IsUse;
import com.junzhiit.nengji.model.enums.OrderStatus;
import com.junzhiit.nengji.model.enums.OrderType;
import com.junzhiit.nengji.model.enums.OrdersDataHistoryStatus;
import com.junzhiit.nengji.model.enums.PayHistoryType;
import com.junzhiit.nengji.model.enums.PayWay;
import com.junzhiit.nengji.model.enums.PostageType;
import com.junzhiit.nengji.model.enums.RechargeConfigureGiveType;
import com.junzhiit.nengji.model.enums.RechargeRecordStatus;
import com.junzhiit.nengji.model.enums.TransactionType;
import com.junzhiit.nengji.model.enums.UserGoodsType;
import com.junzhiit.nengji.model.enums.UserVipType;
import com.junzhiit.nengji.model.enums.VipHistoryStatus;

import cn.hutool.json.JSONUtil;

@Service
public class OrdersServiceImpl extends BaseServiceImpl implements OrdersService {

	@Autowired
	private OrdersDAO ordersDAO;

	@Autowired
	private OrdersGoodsDAO ordersGoodsDAO;

	@Autowired
	private OrdersGoodsService ordersGoodsService;

	@Autowired
	private GoodsDAO goodsDAO;

	@Autowired
	private AddressDAO addressDAO;

	@Autowired
	private UserDAO userDAO;

	@Autowired
	private CartDAO cartDAO;

	@Autowired
	private UserGoodsDAO userGoodsDAO;

	@Autowired
	private PayHistoryDAO payHistoryDAO;

	@Autowired
	private SkuContentDAO skuContentDAO;

	@Autowired
	private TransactionService transactionService;

	@Autowired
	private SystemConfigDAO systemConfigDAO;

	@Autowired
	private RebateService rebateService;

	@Autowired
	private CommissionHistoryService commissionHistoryService;

	@Autowired
	private ShopDAO shopDAO;

	@Autowired
	private UserVipDAO userVipDAO;

	@Autowired
	private VipHistoryDAO vipHistoryDAO;

	@Autowired
	private UserConfigDAO userConfigDAO;

	@Autowired
	private UserCouponsDAO userCouponsDAO;
	
	@Autowired
	private OrdersDataHistoryDAO ordersDataHistoryDAO;
	
	@Autowired
	private GoodsDataHistoryDAO goodsDataHistoryDAO;
	
	@Autowired
	private IndustryDAO industryDAO;
	
	@Autowired
	private UserCouponsService userCouponsService;
	
	@Autowired
	private CouponsService couponsService;
	             
	@Autowired
	private UserCacheDAO userCacheDAO;
	
	@Autowired
	private RechargeRecordDAO rechargeRecordDAO;

	@Autowired
	private ShopClientDAO shopClientDAO;
	
	@Autowired
	private ShopsLocatedDAO shopsLocatedDAO;
	
	@Autowired
	private PostageTemplateService postageTemplateService;
	
	@Autowired
	private BalanceHistoryDAO balanceHistoryDAO;
	
	@Autowired
	private RabbitMQService rabbitMQService;

	private final String WECHAT_BODY_KEY = "乐鸽订单";

	// private final String WECHAT_BODY_KEY = "wechat.body";

	@Value("${images.qrcode.order.path}")
	private String qrcodePath;
	
	@Value("${images.data.qrcode.order.path}")
	private String dataQrcodePath;
	
	//阿里云API的bucket名称
	@Value("${oss.backet.name}")
	private String backetName;

	@Override
	public ResultVO findAllOrders(Integer pageNumber, Integer maxPageRow, Integer status, Integer type, String userId) {
		ResultVO result = new ResultVO();
		List<OrdersBO> orderList = ordersDAO.orders(pageNumber, maxPageRow, status, type, userId,null);
		if (orderList.size() == 0) {
			result.setStatus(APICodeStatus.GOODS_LIST_IS_EMPTY);
			result.setMessage("goods list is empty.");
			return result;
		}
		List<OrdersVO> list = new ArrayList<OrdersVO>();
		Boolean isEmpty = true;
		for (OrdersBO ordersBO : orderList) {
			OrdersVO ordersVO = new OrdersVO();
			ordersVO.setId(ordersBO.getId());
			ordersVO.setCreatedTime(ordersBO.getCreatedTime());
			ordersVO.setStatus(ordersBO.getStatus());
			ordersVO.setPostage(ordersBO.getPostage());
			ordersVO.setPayWay(ordersBO.getPayWay());
			ordersVO.setShopName(ordersBO.getShopName());
			ordersVO.setPayMoney(ordersBO.getPayMoney());
			ordersVO.setShopId(ordersBO.getShopId());
			ordersVO.setOrderNumber(ordersBO.getOrderNumber());
			ordersVO.setShopHeadImgUrl(ordersBO.getShopHeadImgUrl());
			ordersVO.setShopOrderNumber(ordersBO.getShopOrderNumber());
			ordersVO.setLogisticsNumber(ordersBO.getLogisticsNumber());
			ordersVO.setType(ordersBO.getType());
			List<OrdersGoodsBO> orderGoodsBOList = ordersGoodsDAO.getOrderGoods(ordersBO.getId());
			for (OrdersGoodsBO orderGoodsBO : orderGoodsBOList) {
				OrdersGoodsVO ordersGoodsVO = new OrdersGoodsVO();
				ordersGoodsVO.setId(orderGoodsBO.getId());
				ordersGoodsVO.setCoverImage(orderGoodsBO.getCoverImage());
				ordersGoodsVO.setType(orderGoodsBO.getType());
				ordersGoodsVO.setCode(orderGoodsBO.getCode());
				ordersGoodsVO.setBarcode(orderGoodsBO.getBarcode());
				ordersGoodsVO.setName(orderGoodsBO.getName());
				ordersGoodsVO.setNumber(orderGoodsBO.getNumber());
				ordersGoodsVO.setIsOpenSku(orderGoodsBO.getIsOpenSku());
				ordersGoodsVO.setStandard(orderGoodsBO.getStandard());
				ordersGoodsVO.setPrice(orderGoodsBO.getPrice());
				ordersGoodsVO.setReferencePrice(orderGoodsBO.getReferencePrice());
				ordersVO.addGoods(ordersGoodsVO);
				isEmpty = false;
			}

			list.add(ordersVO);
		}
		if (isEmpty) {
			result.setStatus(APICodeStatus.GOODS_LIST_IS_EMPTY);
			result.setMessage("Goods empty.");
			return result;
		}
		int totalCount = ordersDAO.getGoodsTotalCount(status, userId, type);
		ListVO listVO = new ListVO();
		listVO.setIndex(pageNumber);
		listVO.setCount(totalCount);
		listVO.setList(list);

		result.setData(listVO);
		result.setMessage("order success.");
		return result;
	}

	@Override
	public ResultVO changeStatus(String id, Integer status) {
		ResultVO result = new ResultVO();
		try {
			Orders orders = new Orders();
			orders.setId(id);
			orders.setStatus(status);
			if(status == OrderStatus.COMPLETE.toIntValue()){
				orders.setCompleteTime(new Date());
			}
			//还原优惠劵状态
			if(status == OrderStatus.CANCEL.toIntValue() || 
					status == OrderStatus.FAILIN.toIntValue() || 
					status == OrderStatus.FAIL.toIntValue()){
				userCouponsDAO.updateUserCoupons(id);
			}
			if(status == OrderStatus.PAID.toIntValue()){
				orders.setPayTime(new Date());
			}
			result.setData(ordersDAO.update(orders));
		} catch (Exception e) {
			result.setStatus(APICodeStatus.ORDER_UPDATE_STATUS_IS_FAIL);
			result.setMessage("order update status fail.");
			e.printStackTrace();
		}
		return result;
	}

	@Override
	public ResultVO findOrderInfo(String userId, String goods,String areaCode) {
		ResultVO result = new ResultVO();
		OrderInfoVO orderInfoVO = new OrderInfoVO();

		List<OrderInfoGoodsVO> goodsList = new ArrayList<OrderInfoGoodsVO>();

		// 商品
		String[] goodsArray = goods.split(";");// number_goodsId_shopId_skuContentId
		Boolean isGoodsEmpty = true;
		Map<String, OrdersShopVO> shopIds = new HashMap<String, OrdersShopVO>();
		Set<String> shopIdList = new HashSet<String>();
		//店铺商品集合
		Map<String,Map<GoodsBO,Integer>> goodsMap = new HashMap<String,Map<GoodsBO,Integer>>();
		try {
			for (int i = 0; i < goodsArray.length; i++) {
				String[] goodsInfo = goodsArray[i].split("_");

				Integer number = Integer.valueOf(goodsInfo[0]);
				GoodsBO goodsBO = null;
				if (goodsInfo.length == 4) {
					goodsBO = goodsDAO.getGoodsByBarcode(userId, goodsInfo[2], goodsInfo[1], goodsInfo[3]);// sku
				} else {
					goodsBO = goodsDAO.getGoodsInfo(userId, goodsInfo[2], goodsInfo[1]);// not sku
				}
				
				if(goodsMap.containsKey(goodsBO.getShopId())){
					Map<GoodsBO,Integer> goodsAndNumber = goodsMap.get(goodsBO.getShopId());
					goodsAndNumber.put(goodsBO, number);
				}else{
					Map<GoodsBO,Integer> goodsAndNumber = new HashMap<GoodsBO,Integer>();
					goodsAndNumber.put(goodsBO, number);
					goodsMap.put(goodsBO.getShopId(), goodsAndNumber);
				}
				
				shopIdList.add(goodsInfo[2]);
				// shop info
				OrdersShopVO shopInfo = new OrdersShopVO();
				shopInfo.setShopId(goodsBO.getShopId());
				shopInfo.setShopName(goodsBO.getShopName());
				shopInfo.setShopLogo(goodsBO.getShopHeadImgUrl());
				shopInfo.setType(goodsBO.getShopType());
				shopInfo.setPostageType(goodsBO.getPostageType());
				if (goodsBO.getPostageType() == PostageType.UNIFY.toIntValue()) {
					shopInfo.setPostagePrice(goodsBO.getPostagePrice());
				} else if (goodsBO.getPostageType() == PostageType.TEMPLATE.toIntValue()) {
					shopInfo.setPostageTemplateId(goodsBO.getPostageTemplateId());
				}
				shopIds.put(goodsInfo[2], shopInfo);

				// goods info
				if (goodsBO != null && StringUtils.isNotBlank(goodsBO.getId())) {
					OrderInfoGoodsVO orderInfoGoodsVO = new OrderInfoGoodsVO();
					BeanUtils.copyProperties(goodsBO, orderInfoGoodsVO);
					orderInfoGoodsVO.setNumber(number);
					

					goodsList.add(orderInfoGoodsVO);
					isGoodsEmpty = false;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			isGoodsEmpty = true;
		}
		if (isGoodsEmpty) {
			result.setStatus(APICodeStatus.GOODS_NOT_FOUND);
			result.setMessage("Goods not found.");
			return result;
		}

		Double shopPostageMoney = 0.00;// 店铺运费
		Double shopGoodMoney = 0.00;
		Double sumPostageMoney = 0.00;// 订单总运费
		Double sumPayMoney = 0.0;// 实际支付金额
		Integer sumNumber = 0;
		
		//店铺邮费
		FreightVO freightVO = postageTemplateService.freight(userId, areaCode,goodsMap);
		
//		if(!freightVO.isNoSupport()){
//			orderInfoVO.setNoSupportList(freightVO.getNoSupportList());
//			result.setData(orderInfoVO);
//			return result;
//		}
		
//		List<Double> postageArray = new ArrayList<Double>();
		String noSupport = freightVO.getNoSupportGoodsIds();
		List<OrdersShopVO> shopList = new ArrayList<OrdersShopVO>();
		for (OrdersShopVO ordersShopVO : shopIds.values()) {
			for (OrderInfoGoodsVO orderInfoGoodsVO : goodsList) {
				if (orderInfoGoodsVO.getShopId().equals(ordersShopVO.getShopId())) {
					if(noSupport.indexOf(orderInfoGoodsVO.getId())>=0){
						orderInfoGoodsVO.setNoSupport(false);
					}
					ordersShopVO.addGoods(orderInfoGoodsVO);
					// 商品总价
					shopGoodMoney += orderInfoGoodsVO.getPrice() * orderInfoGoodsVO.getNumber();
					sumNumber += orderInfoGoodsVO.getNumber();
					if (orderInfoGoodsVO.getPostagePrice() == null) {
						orderInfoGoodsVO.setPostagePrice(0.0);
					}
//					if (orderInfoGoodsVO.getPostageType() == PostageType.POSTAGE.toIntValue()) {
//						postageArray.add(0.0);
//					} else {
//						postageArray.add(orderInfoGoodsVO.getPostagePrice());
//					}
				}
			}

//			shopPostageMoney = Collections.max(postageArray);
			if(freightVO.isNoSupport()){
				shopPostageMoney = freightVO.getFreightMap().get(ordersShopVO.getShopId());
			}else{
				shopPostageMoney = 0.0;
			}
			
			ordersShopVO.setPostage(shopPostageMoney);
			ordersShopVO.setRealMoney(shopGoodMoney);
			ordersShopVO.setPayMoney(Format.decimal(shopGoodMoney + shopPostageMoney));
			ordersShopVO.setSumNumber(sumNumber);

			shopList.add(ordersShopVO);
			sumPostageMoney += shopPostageMoney;
			sumPayMoney += shopGoodMoney;

			shopPostageMoney = 0.00;
			shopGoodMoney = 0.00;
			sumNumber = 0;
		}
		sumPayMoney += sumPostageMoney;
		orderInfoVO.setPostage(Format.decimal(sumPostageMoney));// 总运费
		orderInfoVO.setSumMoney(Format.decimal(sumPayMoney));// 支付金额

		orderInfoVO.setShop(shopList);

		/**
		 * 以下内容为新增部分
		 */
		// 优惠劵信息查询，当前用户在当前商家中可用的优惠劵以及总部的优惠劵
		List<Shop> shoList = shopDAO.getShop(shopIdList.iterator());
		StringBuffer findInShopSet = new StringBuffer();
		StringBuffer findInChainIdSet = new StringBuffer();
		for(Shop s:shoList){
			if(s.getIsChain()!=null){
				if(s.getIsChain() == Is.YES.toIntValue()){
					findInChainIdSet.append(s.getChainId()+",");
				}
			}
			findInShopSet.append(s.getId()+",");
		}
		if(findInShopSet.length()>1){
			findInShopSet.deleteCharAt(findInShopSet.length()-1);
		}
		if(findInChainIdSet.length()>1){
			findInChainIdSet.deleteCharAt(findInChainIdSet.length()-1);
		}
		
		List<UserCouponsInfoBO> couponsList = userCouponsDAO.getCouponsByUserIdAndShopId(userId, findInShopSet.toString(),findInChainIdSet.toString());
		coupons: for (int i = 0; i < couponsList.size(); i++) {
			UserCouponsInfoBO ucBO = couponsList.get(i);
			if (ucBO.getThreshold().equals(CouponFullSubtraction.UNRESTRICTED.toIntValue())) {
				continue;
			}
			if (ucBO.getPlatform().equals(CouponsPlatform.INTERNAL.toIntValue())) {
				if (ucBO.getFullPriceReduction() > sumPayMoney) {
					couponsList.remove(ucBO);
					continue;
				}
			}else{
				for(int t =0;t<shopList.size();t++){
					OrdersShopVO sbo = shopList.get(t);
					if (sbo.getShopId().equals(ucBO.getShopId())) {
						if (ucBO.getThreshold().equals(CouponFullSubtraction.FULL_SUBTRACTION.toIntValue())) {
							if (ucBO.getFullPriceReduction() > sbo.getRealMoney()) {
								couponsList.remove(ucBO);
								continue coupons;
							}
						}
					}
				}
			}
		}
		orderInfoVO.setCouponsDetails(couponsService.formatCoupons(couponsList));
		/**
		 * 以上内容为新增部分
		 */
		// 地址
		Address address = addressDAO.getDefalutAddress(userId);
		if (address != null && StringUtils.isNotBlank(address.getId())) {
			AddressVO addressVO = new AddressVO();
			addressVO.setId(address.getId());
			addressVO.setName(address.getName());
			addressVO.setAddress(address.getAddress());
			addressVO.setArea(address.getArea());
			addressVO.setIsChecked(address.getIsChecked());
			addressVO.setPhone(address.getPhone());
			addressVO.setAreaCode(address.getAreaCode());
			orderInfoVO.setAddress(addressVO);
		} else {
			result.setStatus(APICodeStatus.ADDRESS_IS_NULL);
			result.setMessage("Address is null.");
			orderInfoVO.setAddress(null);
		}
		//用户配置信息
		UserConfigVO userConfigVO = new UserConfigVO();
		UserConfig userConfig = userConfigDAO.getUserConfig(userId);
		BeanUtils.copyProperties(userConfig,userConfigVO);
		
		orderInfoVO.setUserConfig(userConfigVO);
		
		result.setData(orderInfoVO);
		return result;
	}

	@Override
	public ResultVO findShopOrderInfo(String userId, String goods) {
		ResultVO result = new ResultVO();
		OrderInfoVO orderInfoVO = new OrderInfoVO();

		List<OrderInfoGoodsVO> goodsList = new ArrayList<OrderInfoGoodsVO>();
		// 商品
		String[] goodsArray = goods.split(";");// number_goodsId_shopId_skuContentId
		Boolean isGoodsEmpty = true;
		Map<String, OrdersShopVO> shopIds = new HashMap<String, OrdersShopVO>();
		List<String> shopIdList = new ArrayList<String>();
		try {
			for (int i = 0; i < goodsArray.length; i++) {
				String[] goodsInfo = goodsArray[i].split("_");

				Integer number = Integer.valueOf(goodsInfo[0]);
				GoodsBO goodsBO = null;
				if (goodsInfo.length == 4) {
					goodsBO = goodsDAO.getGoodsByBarcode(userId, goodsInfo[2], goodsInfo[1], goodsInfo[3]);// sku
				} else {
					goodsBO = goodsDAO.getGoodsInfo(userId, goodsInfo[2], goodsInfo[1]);// not sku
				}
				shopIdList.add(goodsInfo[2]);
				// shop info
				OrdersShopVO shopInfo = new OrdersShopVO();
				shopInfo.setShopId(goodsBO.getShopId());
				shopInfo.setShopName(goodsBO.getShopName());
				shopInfo.setShopLogo(goodsBO.getShopHeadImgUrl());
				shopInfo.setType(goodsBO.getShopType());
				shopIds.put(goodsInfo[2], shopInfo);

				// goods info
				if (goodsBO != null && StringUtils.isNotBlank(goodsBO.getId())) {
					OrderInfoGoodsVO orderInfoGoodsVO = new OrderInfoGoodsVO();
					BeanUtils.copyProperties(goodsBO, orderInfoGoodsVO);
					orderInfoGoodsVO.setNumber(number);

					goodsList.add(orderInfoGoodsVO);
					isGoodsEmpty = false;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			isGoodsEmpty = true;
		}
		if (isGoodsEmpty) {
			result.setStatus(APICodeStatus.GOODS_NOT_FOUND);
			result.setMessage("Goods not found.");
			return result;
		}

		Double shopGoodMoney = 0.00;
		List<OrdersShopVO> shopList = new ArrayList<OrdersShopVO>();
		for (OrdersShopVO ordersShopVO : shopIds.values()) {
			for (OrderInfoGoodsVO orderInfoGoodsVO : goodsList) {
				if (orderInfoGoodsVO.getShopId().equals(ordersShopVO.getShopId())) {
					ordersShopVO.addGoods(orderInfoGoodsVO);
					// 商品总价
					shopGoodMoney += orderInfoGoodsVO.getPrice() * orderInfoGoodsVO.getNumber();

				}
			}
			ordersShopVO.setPayMoney(shopGoodMoney);
			shopList.add(ordersShopVO);
		}
		orderInfoVO.setShop(shopList);

		/**
		 * 以下内容为新增部分
		 */
		// 优惠劵信息查询，当前用户在当前商家中可用的优惠劵以及总部的优惠劵
		List<Shop> shoList = shopDAO.getShop(shopIdList.iterator());
		StringBuffer findInShopSet = new StringBuffer();
		StringBuffer findInChainIdSet = new StringBuffer();
		for(Shop s:shoList){
			if(s.getIsChain()!=null){
				if(s.getIsChain() == Is.YES.toIntValue()){
					findInChainIdSet.append(s.getChainId()+",");
				}
			}
			findInShopSet.append(s.getId()+",");
		}
		if(findInShopSet.length()>1){
			findInShopSet.deleteCharAt(findInShopSet.length()-1);
		}
		if(findInChainIdSet.length()>1){
			findInChainIdSet.deleteCharAt(findInChainIdSet.length()-1);
		}
		
		List<UserCouponsInfoBO> couponsList = userCouponsDAO.getCouponsByUserIdAndShopId(userId, findInShopSet.toString(),findInChainIdSet.toString());
		coupons: for (int i = 0; i < couponsList.size(); i++) {
			UserCouponsInfoBO ucBO = couponsList.get(i);
			if (ucBO.getThreshold().equals(CouponFullSubtraction.UNRESTRICTED.toIntValue())) {
				continue;
			}
			if (ucBO.getPlatform().equals(CouponsPlatform.INTERNAL.toIntValue())) {
				if (ucBO.getFullPriceReduction() > shopGoodMoney) {
					couponsList.remove(ucBO);
					continue;
				}
			}else{
				for(int t =0;t<shopList.size();t++){
					OrdersShopVO sbo = shopList.get(t);
					if (sbo.getShopId().equals(ucBO.getShopId())) {
						if (ucBO.getThreshold().equals(CouponFullSubtraction.FULL_SUBTRACTION.toIntValue())) {
							if (ucBO.getFullPriceReduction() > sbo.getPayMoney()) {
								couponsList.remove(ucBO);
								continue coupons;
							}
						}
					}
				}
			}
		}
		orderInfoVO.setCouponsDetails(couponsService.formatCoupons(couponsList));
		/**
		 * 以上内容为新增部分
		 */
		
		//用户配置信息
		UserConfigVO userConfigVO = new UserConfigVO();
		UserConfig userConfig = userConfigDAO.getUserConfig(userId);
		BeanUtils.copyProperties(userConfig,userConfigVO);
				
		orderInfoVO.setUserConfig(userConfigVO);

		result.setData(orderInfoVO);
		return result;
	}

	@Override
	public ResultVO orderInfo(String orderId) {
		ResultVO result = new ResultVO();
		OrdersBO ordersBO = ordersDAO.findOrderId(orderId);
		if (ordersBO == null) {
			throw new OrdersNotFoundException("没找到订单");
		}
		List<OrdersGoodsBO> ordersGoodsBOList = ordersGoodsDAO.getOrderGoods(orderId);
		if (ordersGoodsBOList != null && ordersGoodsBOList.size() == 0) {
			throw new OrdersGoodsNotFoundException("订单商品没找到");
		}

		OrdersVO ordersVO = new OrdersVO();
		BeanUtils.copyProperties(ordersBO, ordersVO);
		List<OrdersGoodsVO> ordersGoodsVOList = new ArrayList<OrdersGoodsVO>();
		Double goodsPrice = 0.00;
		for (OrdersGoodsBO ordersGoodsBO : ordersGoodsBOList) {
			if (ordersGoodsBO.getPrice() != null) {
				goodsPrice += (ordersGoodsBO.getPrice()*ordersGoodsBO.getNumber());
			}
			OrdersGoodsVO ordersGoodsVO = new OrdersGoodsVO();
			BeanUtils.copyProperties(ordersGoodsBO, ordersGoodsVO);
			ordersGoodsVOList.add(ordersGoodsVO);
		}
		ordersVO.setGoodsPrice(Format.decimal(goodsPrice));
		ordersVO.setGoods(ordersGoodsVOList);
		ordersVO.setAddress(ordersBO.getArea() + " " + ordersBO.getAddress());

		result.setData(ordersVO);
		return result;
	}

	@Override
	public ResultVO onlinePaySuccess(String orderNumber) {
		ResultVO result = new ResultVO();
		List<Orders> list = ordersDAO.getOrderByOrderNumber(orderNumber);
		if (list.size() < 0) {
			throw new OrdersNotFoundException("订单没找到");
		}
		OrdersPaySuccessVO ordersPaySuccessVO = new OrdersPaySuccessVO();
		Double payMoney = 0.00;
		for (Orders orders : list) {
			ordersPaySuccessVO.setStatus(orders.getStatus());
			ordersPaySuccessVO.setOrderNumber(orders.getOrderNumber());
			ordersPaySuccessVO.setPayTime(orders.getPayTime());
			payMoney += orders.getPayMoney();
		}
		ordersPaySuccessVO.setPayMoney(Format.decimal(payMoney));
		result.setData(ordersPaySuccessVO);
		return result;
	}

	@Override
	public ResultVO offlinePaySuccess(String orderNumber) {
		ResultVO result = new ResultVO();
		OrdersBO ordersBO = ordersDAO.findOrderOffline(orderNumber);
		if (ordersBO == null) {
			throw new OrdersNotFoundException("订单没找到");
		}
		OrdersPaySuccessVO ordersPaySuccessVO = new OrdersPaySuccessVO();
		BeanUtils.copyProperties(ordersBO, ordersPaySuccessVO);
		Double money = Format.decimal(ordersPaySuccessVO.getPrice()*ordersPaySuccessVO.getNumber());
		ordersPaySuccessVO.setGoodsMoney(money);

		// String validationCode = ordersPaySuccessVO.getValidationCode();
		// try {
		// String passwordKeyValue =
		// PropertiesUtil.getProperties(Constants.KEY_PROPERTIES_FOR_SYSTEM,
		// Constants.SYSTEM_KEY_FOR_PASSOWRD);
		// String sign = AESUtil.decrypt(validationCode, passwordKeyValue);
		// ordersPaySuccessVO.setValidationCode(sign);
		// } catch (Exception e) {
		// e.printStackTrace();
		// }
		result.setData(ordersPaySuccessVO);
		return result;
	}

	@Transactional
	public ResultVO createOrder(HttpServletRequest request, CreateOrderVO createOrderVO) {
		ResultVO result = new ResultVO();
		UserBO userBO = userDAO.findUserId(createOrderVO.getUserId());
		if (userBO == null || StringUtils.isBlank(userBO.getId())){
			throw new UserNotFoundException("User not found");
		}
		
		// 可使用优惠劵的商品集合	
//		List<Goods> goodsDiscount = new ArrayList<Goods>();
		// 可使用优惠劵商品及总价格集合
//		Map<String,Double> goodsDiscountMap = new HashMap<String,Double>();
		// 新增检验商品库存
		if (StringUtils.isNoneBlank(createOrderVO.getGoods())) {
			String goodsStr = createOrderVO.getGoods().replace(":", ";");
			String[] goodsArray = goodsStr.split(";");
			List<String> list = new ArrayList<>();
			for (int i = 0; i < goodsArray.length; i++) {
				String[] goodsObj = goodsArray[i].split("_");// number_price_goodsId_skuContentId
				Integer number = Integer.valueOf(goodsObj[0]);
				String goodsId = goodsObj[2];
				String skuContentId = "";
				if (goodsObj.length == 4) {
					skuContentId = goodsObj[3];
				}
				Integer stock = 0;
				Goods goods = goodsDAO.query(goodsId);
				if (goods == null) {
					throw new GoodsNotFoundException("商品没找到");
				}
//				if(goods.getIsOpenRebate() == Is.NO.toIntValue() && goods.getIsOpenSell() == Is.NO.toIntValue()){
//					goodsDiscount.add(goods);
//					Double total = number*Double.valueOf(goodsObj[1]);
//					goodsDiscountMap.put(goods.getId(), total);
//				}
				
				if (StringUtils.isNotBlank(skuContentId)) {
					SkuContent skuContent = skuContentDAO.query(skuContentId);
					if (skuContent == null) {
						throw new SkuContentNotFoundException("sku规格组合没找到");
					}
					stock = skuContent.getStock();
				} else {
					stock = goods.getStock();
				}
				if (number > stock) {
					list.add(goods.getName());
				}
			}
			if (list.size() > 0) {
				result.setData(list);
				result.setStatus(APICodeStatus.GOODS_UNDERSTOCK);
				result.setMessage("goods understock ");
				return result;
			}
		}
		//将可使用优惠卷集合按照店铺分类好类
//		Map<String,Set<String>> shopGoodsMap = new HashMap<String,Set<String>>();
		//得出店铺普通商品总价格
//		Map<String,Double> shopGoodsTotalMoney = new HashMap<String,Double>();
		//普通商品交易总金额(只包含普通商品,可使用优惠劵的商品)
//		Double transactionTotalMoney = new Double(0);
//		for(int i = 0,t = goodsDiscount.size();i<t;i++){
//			Goods g = goodsDiscount.get(i);
//			String id = g.getId();
//			String shopId = g.getShopId();
//			
//			Double money = goodsDiscountMap.get(id);
//			
//			transactionTotalMoney += money;
//			
//			if(shopGoodsTotalMoney.containsKey(shopId)){
//				Double totalMoney =  shopGoodsTotalMoney.get(shopId);
//				totalMoney += money;
//				shopGoodsTotalMoney.put(shopId, totalMoney);
//			}else{
//				shopGoodsTotalMoney.put(shopId, money);
//			}
//			
//			if(shopGoodsMap.containsKey(shopId)){
//				Set<String> set =  shopGoodsMap.get(shopId);
//				set.add(id);
//			}else{
//				Set<String> set = new HashSet<String>();
//				set.add(id);
//				shopGoodsMap.put(shopId, set);
//			}
//		}
		 
		Orders newOrder = new Orders();
		//拆分前端传入各种参数
		String orderNumber = NumberUtils.getOrderlNumber();
		String[] shops = createOrderVO.getShopId().split(";");
		String[] realMoney = createOrderVO.getRealMoney().split("_");
		String[] postage = createOrderVO.getPostage().split("_");
		String[] payMoney = createOrderVO.getPayMoney().split("_");
		//店铺优惠劵集合
		String[] coupons = createOrderVO.getUserCouponsIds().split(";");
		
		String[] discountMoney = createOrderVO.getDiscountMoney().split("_");
		//商品ID集合  number_price_goodsId_skuContentId
		String[] goodsIds = createOrderVO.getGoods().split(":");
		//店铺优惠劵(使用的优惠劵按照店铺分好类,由于限制一个店铺只能用一张优惠劵,所以一个店铺ID只对应了一个店铺优惠劵)
		Map<String,String> couponsMap = new HashMap<String,String>();
		//此状态位标识是否是使用总部优惠劵，默认否。
		boolean isEquable = false;
		//交易总金额(含分销返利)
		Double totalPayMoney = new Double(0);
		for(int i = 0;i<payMoney.length;i++){
			String pay = payMoney[i];
			totalPayMoney += Double.parseDouble(pay);
		}
		//如果有优惠劵则按照店铺、优惠劵存储。
		if(StringUtils.isNotBlank(createOrderVO.getUserCouponsIds())){
			for(String s:coupons){
				String []src = s.split("_");
				if(src.length>1){
					couponsMap.put(src[0], src[1]);
				}
			}
		}else{
			isEquable = true;
		}
		//实际交易总金额(用于最后发起微信支付)
		Double totalFee = 0.0;
		
		
		for(int i =0,t =shops.length;i<t;i++){
			String shopIds = shops[i];
			Orders order = new Orders();
			order.setShopId(shopIds);
			order.setUserId(createOrderVO.getUserId());
			order.setAddressId(createOrderVO.getAddressId());
			order.setOrderNumber(orderNumber);//总订单号
			order.setShopOrderNumber(NumberUtils.getOrderlNumber());//店铺订单号
			order.setRealMoney(Double.valueOf(realMoney[i]));//优惠前金额
			order.setPostage(Double.valueOf(postage[i]));//运费
			order.setPayMoney(Double.valueOf(payMoney[i]));//支付金额未优惠
			order.setStatus(OrderStatus.WAIT.toIntValue());
			order.setRemark(createOrderVO.getRemark());
			order.setType(createOrderVO.getType());
			
			/*if(shops.length <= 1){
				order.setDeductionMoney(createOrderVO.getDeductionMoney());
			}else{
				order.setDeductionMoney(Double.valueOf(payMoney[i]) / totalPayMoney * createOrderVO.getDeductionMoney());
			}*/
			
			// 以下过程设置优惠金额
			if (isEquable) {
				//取出店铺所有普通商品的支付金额
//				Double shoptotalPayMoney = shopGoodsTotalMoney.get(shopIds);
//				if(shoptotalPayMoney == null){
//					shoptotalPayMoney = new Double(0);
//				}
				// 店铺所有普通商品的支付金额/所有普通商品支付金额*总部优惠金额(如果没有使用总部优惠卷则这里总部优惠卷取出的是0)
				
				//店铺优惠前金额/总支付金额*总部优惠金额(如果没有使用总部优惠卷则这里总部优惠卷取出的是0)
				Double ratio = (order.getRealMoney() / totalPayMoney) * createOrderVO.getInternalDiscountMoney();
				ratio = Format.decimal(ratio);
				//存入的是普通商品被优惠的金额
				order.setCouponsMoney(ratio);
				order.setUserCouponsId(createOrderVO.getInternalDiscountId());
			} else {
				//discountMoney 如果该店铺没有用优惠劵则此处应该为0
				order.setCouponsMoney(Double.parseDouble(discountMoney[i]));
				order.setUserCouponsId(couponsMap.get(shopIds));
			}
			//重新计算支付金额(减去优惠金额，加上运费)
			Double operation = order.getPayMoney()-order.getCouponsMoney();
			if(operation<0){
				operation = 0.0;
			}
			Double finalPayMoney = Format.decimal(operation+order.getPostage());
			
			if(finalPayMoney<0){
				finalPayMoney = 0.0;
			}
			
			order.setPayMoney(finalPayMoney);
			
			order.setPayWay(PayWay.toValue(createOrderVO.getPayWay()).toIntValue());
			
			if(createOrderVO.getType() == OrderType.EXTRACT.toIntValue()){
				order.setConsumeName(createOrderVO.getConsumeName());
				order.setConsumePhone(createOrderVO.getConsumePhone());
			}
			
			newOrder = ordersDAO.insert(order);
			
			if(couponsMap.containsKey(shopIds)){
				String userCoupons = couponsMap.remove(shopIds);
				couponsMap.put(newOrder.getId(), userCoupons);
			}
			
			totalFee += newOrder.getPayMoney();

			ordersGoodsService.add(goodsIds[i], newOrder.getId(), createOrderVO.getUserId(),shopIds);
		}
		//清理不需要的对象
//		goodsDiscount.clear();
//		goodsDiscountMap.clear();
//		shopGoodsMap.clear();
//		shopGoodsTotalMoney.clear();
		
		// 删除购物车的商品
		if (StringUtils.isNoneBlank(createOrderVO.getCartIds())) {
			cartDAO.batchDeleteGoods(createOrderVO.getCartIds().split(","));
		}
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("orderNumber", orderNumber);
		map.put("orderId", newOrder.getId());
		
		//现金分支付
		Double couponsMoney = 0.0;
		if(createOrderVO.getPayWay() == PayWay.CASH.toIntValue() || createOrderVO.getPayWay() == PayWay.REDEEM.toIntValue()){
			if(createOrderVO.getPayWay() == PayWay.CASH.toIntValue()){
				if(userBO.getCurrentMoney() < totalFee){
					throw new MoneyNotMuchException("余额不足");
				}
			}else if(createOrderVO.getPayWay() == PayWay.REDEEM.toIntValue()){
				if(userBO.getWithdrawalMoney() < totalFee){
					throw new MoneyNotMuchException("余额不足");
				}
			}
			
			List<Orders> list = ordersDAO.getOrderByPay(userBO.getId(), orderNumber);
			for (Orders orders : list) {
				if (list.size() < 0)
					throw new OrderNotFoundException("Orders not found");

				couponsMoney += orders.getCouponsMoney();
				String userId = userBO.getId();
				orders.setPayTime(new Date());
				orders.setPayWay(createOrderVO.getPayWay());
				orders.setStatus(OrderStatus.PAID.toIntValue());
				ordersDAO.update(orders);
				
				//检查是否满足享有二级分润条件
				SystemConfig systemConfig = systemConfigDAO.find();
				if (systemConfig.getIsOpenMemberSell() == Is.YES.toIntValue() && userBO.getIsMemberSell() == Is.NO.toIntValue()) {
					Double value = ordersDAO.sumPayMoney(userId);
					if (value >= systemConfig.getSellValue()) {
						User userParams = userDAO.query(userId);
						userParams.setIsMemberSell(Is.YES.toIntValue());
						userDAO.update(userParams);
					}
				}
				
				OrdersDataHistory ordersDataHistory = new OrdersDataHistory();
				ordersDataHistory.setOrdersId(orders.getId());
				ordersDataHistory.setShopId(orders.getShopId());
				ordersDataHistory.setOrderNumber(orders.getOrderNumber());
				ordersDataHistory.setShopOrderNumber(orders.getShopOrderNumber());
				ordersDataHistory.setRealMoney(orders.getRealMoney());
				ordersDataHistory.setPayMoney(totalPayMoney);
				ordersDataHistory.setFactPayMoney(orders.getPayMoney());
				//ordersDataHistory.setDeductionMoney(orders.getDeductionMoney());//积分抵扣
				ordersDataHistory.setPostage(orders.getPostage());
				ordersDataHistory.setStatus(OrdersDataHistoryStatus.CLOSE.toIntValue());
				ordersDataHistory.setPayWay(createOrderVO.getPayWay());
				UserCoupons userCoupons = userCouponsDAO.getUserCoupons(userId,orders.getId(),orderNumber);
					if(userCoupons != null){
						ordersDataHistory.setCouponsId(orders.getUserCouponsId());
						ordersDataHistory.setCouponsType(userCoupons.getCouponsType());
						if(userCoupons.getCouponsType() == CouponsType.SHOP.toIntValue()){
							ordersDataHistory.setCouponsMoney(orders.getCouponsMoney());
						}else{
							Double avg = orders.getPayMoney() / totalFee * orders.getCouponsMoney();
							ordersDataHistory.setCouponsMoney(Format.decimal(avg));
						}
					}
				OrdersDataHistory ordersDataHistoryparams = ordersDataHistoryDAO.insert(ordersDataHistory);
				
				int number=0;
				List<OrdersGoods> ordersGoodsList = ordersGoodsDAO.getOrderGoodsByOrderId(orders.getId());
				for (OrdersGoods ordersGoods : ordersGoodsList) {

					number += ordersGoods.getNumber();
					//查询商品信息
					Goods goods = goodsDAO.query(ordersGoods.getGoodsId());
					//查询店铺信息
					Shop shop =  shopDAO.query(goods.getShopId());
					if (goods.getIsOpenSku() == Is.YES.toIntValue()) {
						SkuContent skuContent = skuContentDAO.query(ordersGoods.getSkuContentId());
						skuContent.setStock(skuContent.getStock() - ordersGoods.getNumber());// 库存
						skuContentDAO.update(skuContent);

						
						//添加待结算金额
						//Shop shop =  shopDAO.query(goods.getShopId());
						Double sumGoodsMoney = skuContent.getPrice() * ordersGoods.getNumber();
						Double waitSumMoney = sumGoodsMoney - (sumGoodsMoney * goods.getProfit() /100);
						if(goods.getIsOpenRebate() == Is.YES.toIntValue() && goods.getIsOpenSell() == Is.YES.toIntValue()){
							shop.setAccumulativeMoney(shop.getAccumulativeMoney()+waitSumMoney);
							shop.setMonthIncomeMoney(shop.getMonthIncomeMoney()+waitSumMoney);
							shop.setWithdrawalMoney(shop.getWithdrawalMoney()+waitSumMoney);
						}else{
							shop.setWaitSumMoney(shop.getWaitSumMoney()+waitSumMoney);
						}
						shopDAO.update(shop);
						
						OrdersDataHistory dataHistory = ordersDataHistoryDAO.query(ordersDataHistoryparams.getId());
						Industry industry = industryDAO.query(shop.getIndustryId());
						dataHistory.setShopMoney(dataHistory.getShopMoney()+waitSumMoney); 
						dataHistory.setProfitMoney(dataHistory.getProfitMoney() + (sumGoodsMoney - waitSumMoney));
						dataHistory.setIndustryFullName(industry.getName());
						ordersDataHistoryDAO.update(dataHistory);
						
						GoodsDataHistory goodsDataHistory = new GoodsDataHistory();
						goodsDataHistory.setGoodsId(goods.getId());
						goodsDataHistory.setShopId(goods.getShopId());
						goodsDataHistory.setOrdersDataHistoryId(ordersDataHistoryparams.getId());
						goodsDataHistory.setTypeId(goods.getTypeId());
						goodsDataHistory.setGoodsName(goods.getName());
						goodsDataHistory.setSkuContentName(skuContent.getStandards());
						goodsDataHistory.setNumber(ordersGoods.getNumber());
						goodsDataHistory.setPrice(ordersGoods.getPayMoney());
						goodsDataHistory.setIsOpenRebate(goods.getIsOpenRebate());
						goodsDataHistory.setProfit(goods.getProfit());
						goodsDataHistory.setShopMoney(waitSumMoney);
						goodsDataHistory.setProfitMoney(sumGoodsMoney - waitSumMoney);
						//goodsDataHistory.setCouponsMoney(sumGoodsMoney / dataHistory.getPayMoney() * dataHistory.getCouponsMoney());
						goodsDataHistory.setCouponsMoney(ordersGoods.getCouponsMoney());
						GoodsDataHistory goodsDataHistoryParam = goodsDataHistoryDAO.insert(goodsDataHistory);
						
						//有SKU商品进入排队返利队列
						if(goods.getIsOpenRebate() == Is.YES.toIntValue()){
							for(int i = 0;i<ordersGoods.getNumber();i++){
								//检查是否已经进入返利队列
								OrdersGoods params = ordersGoodsDAO.query(ordersGoods.getId());
								if(params.getIsQueue() == Is.NO.toIntValue()){
									RebateVO rebateVO = new RebateVO();
									rebateVO.setGoodsId(goods.getId());
									rebateVO.setSkuContentId(skuContent.getId());
									rebateVO.setPrice(skuContent.getPrice());
									rebateVO.setShopId(goods.getShopId());
									rebateVO.setUserId(userId);
									rebateVO.setOrderId(ordersGoods.getOrderId());
									rebateVO.setGoodsName(goods.getName());
									rebateVO.setOrderGoodsId(ordersGoods.getId());
									RebateInfo rebateInfo = rebateService.addRebate(rebateVO);
									if (StringUtils.isNoneBlank(rebateInfo.getId())) {
										rebateService.updateRedate(rebateInfo);
									}
								}
							}
						}
						
						if(goods.getIsOpenSell() == Is.YES.toIntValue() && goods.getIsOpenRebate() == Is.YES.toIntValue()){
							//分销
							commissionHistoryService.add(userId, ordersGoods.getId(), userBO.getParentId(),ordersDataHistoryparams.getId(),goodsDataHistoryParam.getId());
						}
						
						goodsDataHistory = goodsDataHistoryDAO.query(goodsDataHistoryParam.getId());
						Double profit = (goodsDataHistory.getPrice()*goodsDataHistory.getNumber()) - goodsDataHistory.getShopMoney(); //利润
						//共分出多少钱
						Double sumMoney = goodsDataHistory.getReferrerMoney() +  goodsDataHistory.getPrimaryBenefitMoney()+goodsDataHistory.getSecondBenefitMoney()+goodsDataHistory.getShopGetBenefitMoney();
						Double grossMargin = profit - sumMoney; //毛利
						Double grossMarginRate = grossMargin / profit * 100;//毛利率
							if(!grossMarginRate.isNaN()){
								goodsDataHistory.setGrossMargin(grossMargin);
								goodsDataHistory.setGrossMarginRate(grossMarginRate);
							}
						goodsDataHistoryDAO.update(goodsDataHistory);
					}else{
						goods.setStock(goods.getStock() - ordersGoods.getNumber());//库存
						
						//添加待结算金额
						//Shop shop =  shopDAO.query(goods.getShopId());
						Double sumGoodsMoney = goods.getPrice() * ordersGoods.getNumber();
						Double waitSumMoney = sumGoodsMoney - (sumGoodsMoney * goods.getProfit() /100);
						if(goods.getIsOpenRebate() == Is.YES.toIntValue() && goods.getIsOpenSell() == Is.YES.toIntValue()){
							shop.setAccumulativeMoney(shop.getAccumulativeMoney()+waitSumMoney);
							shop.setMonthIncomeMoney(shop.getMonthIncomeMoney()+waitSumMoney);
							shop.setWithdrawalMoney(shop.getWithdrawalMoney()+waitSumMoney);
						}else{
							shop.setWaitSumMoney(shop.getWaitSumMoney()+waitSumMoney);
						}
						shopDAO.update(shop);
						
						
						OrdersDataHistory dataHistory = ordersDataHistoryDAO.query(ordersDataHistoryparams.getId());
						Industry industry = industryDAO.query(shop.getIndustryId());
						dataHistory.setShopMoney(dataHistory.getShopMoney()+waitSumMoney); 
						dataHistory.setProfitMoney(dataHistory.getProfitMoney() + (sumGoodsMoney - waitSumMoney));
						dataHistory.setIndustryFullName(industry.getName());
						ordersDataHistoryDAO.update(dataHistory);
						
						GoodsDataHistory goodsDataHistory = new GoodsDataHistory();
						goodsDataHistory.setGoodsId(goods.getId());
						goodsDataHistory.setShopId(goods.getShopId());
						goodsDataHistory.setOrdersDataHistoryId(ordersDataHistoryparams.getId());
						goodsDataHistory.setTypeId(goods.getTypeId());
						goodsDataHistory.setGoodsName(goods.getName());
						goodsDataHistory.setNumber(ordersGoods.getNumber());
						goodsDataHistory.setPrice(ordersGoods.getPayMoney());
						goodsDataHistory.setIsOpenRebate(goods.getIsOpenRebate());
						goodsDataHistory.setProfit(goods.getProfit());
						goodsDataHistory.setShopMoney(waitSumMoney);
						goodsDataHistory.setProfitMoney(sumGoodsMoney - waitSumMoney);
						//goodsDataHistory.setCouponsMoney(sumGoodsMoney / dataHistory.getPayMoney() * dataHistory.getCouponsMoney());
						goodsDataHistory.setCouponsMoney(ordersGoods.getCouponsMoney());
						GoodsDataHistory goodsDataHistoryParam = goodsDataHistoryDAO.insert(goodsDataHistory);
						
						//没有SKU商品进入排队返利队列
						if(goods.getIsOpenRebate() == Is.YES.toIntValue()){
							for(int i = 0;i<ordersGoods.getNumber();i++){
								//检查是否已经进入返利队列
								OrdersGoods params = ordersGoodsDAO.query(ordersGoods.getId());
								if(params.getIsQueue() == Is.NO.toIntValue()){
									RebateVO rebateVO = new RebateVO();
									rebateVO.setGoodsId(goods.getId());
									rebateVO.setPrice(goods.getPrice());
									rebateVO.setShopId(goods.getShopId());
									rebateVO.setUserId(userId);
									rebateVO.setGoodsName(goods.getName());
									rebateVO.setOrderId(ordersGoods.getOrderId());
									rebateVO.setOrderGoodsId(ordersGoods.getId());
									RebateInfo rebateInfo = rebateService.addRebate(rebateVO);
									if (StringUtils.isNoneBlank(rebateInfo.getId())) {
										rebateService.updateRedate(rebateInfo);
									}
								}
							}
						}
						if(goods.getIsOpenSell() == Is.YES.toIntValue() && goods.getIsOpenRebate() == Is.YES.toIntValue()){
							//分销
							commissionHistoryService.add(userId, ordersGoods.getId(), userBO.getParentId(),ordersDataHistoryparams.getId(),goodsDataHistoryParam.getId());
						}
						goodsDataHistory = goodsDataHistoryDAO.query(goodsDataHistoryParam.getId());
						Double profit = (goodsDataHistory.getPrice()*goodsDataHistory.getNumber()) - goodsDataHistory.getShopMoney(); //利润
						//共分出多少钱
						Double sumMoney = goodsDataHistory.getReferrerMoney() +  goodsDataHistory.getPrimaryBenefitMoney()+goodsDataHistory.getSecondBenefitMoney()+goodsDataHistory.getShopGetBenefitMoney();
						Double grossMargin = profit - sumMoney; //毛利
						Double grossMarginRate = grossMargin / profit * 100;//毛利率
							if(!grossMarginRate.isNaN()){
								goodsDataHistory.setGrossMargin(grossMargin);
								goodsDataHistory.setGrossMarginRate(grossMarginRate);
							}
						goodsDataHistoryDAO.update(goodsDataHistory);
					}
					
					goods.setSalesVolume(goods.getSalesVolume()+ordersGoods.getNumber());//销量
					goodsDAO.update(goods);

					// 生成购买记录
					UserGoods userGoods = new UserGoods();
					userGoods.setShopId(orders.getShopId());
					userGoods.setGoodsId(ordersGoods.getGoodsId());
					userGoods.setUserId(userBO.getId());
					userGoods.setType(UserGoodsType.BUY.toIntValue());
					userGoods.setNumber(ordersGoods.getNumber());
					userGoodsDAO.insert(userGoods);
					
					//统计订单数据表毛利
					OrdersDataHistory newOrdersDataHistory =  ordersDataHistoryDAO.query(ordersDataHistoryparams.getId());
					if(newOrdersDataHistory != null){
						Double profit = newOrdersDataHistory.getPayMoney()- newOrdersDataHistory.getPostage() - newOrdersDataHistory.getShopMoney();
						Double sumMoney = newOrdersDataHistory.getShareBenefitMoney() + newOrdersDataHistory.getReferrerMoney()+newOrdersDataHistory.getAgencyBenefit() + newOrdersDataHistory.getAgencyAccount();
						Double grossMargin = profit - sumMoney; //毛利
						Double grossMarginRate = grossMargin / profit * 100;//毛利率
							if(!grossMarginRate.isNaN()){
								newOrdersDataHistory.setGrossMargin(grossMargin);
								newOrdersDataHistory.setGrossMarginRate(grossMarginRate);
							}
						ordersDataHistoryDAO.update(newOrdersDataHistory);
					}
					
					if(goods.getIsOpenSell() == Is.YES.toIntValue() && goods.getIsOpenRebate() == Is.YES.toIntValue()){
						//城市代理数据对接
						Double profitsMoney = ordersGoods.getPayMoney()  * ordersGoods.getProfit() / 100;
						Map<String, Object> contentMap = new HashMap<>();
						contentMap.put("id", ordersGoods.getId());
						contentMap.put("ps", profitsMoney);
						contentMap.put("areaId", shop.getAreaCountyId());
						contentMap.put("payAmount", ordersGoods.getPayMoney());
						contentMap.put("shopOrderNumber", orders.getShopOrderNumber());
						contentMap.put("shopId", shop.getId());
						contentMap.put("shopName", shop.getName());
						String content = JSONUtil.toJsonStr(contentMap);
						rabbitMQService.sendToStoreBusiness(ordersGoods.getId(), content);
					}
				}
				//添加交易记录
				PayHistory payHistory = new PayHistory();
				payHistory.setShopId(orders.getShopId());
				payHistory.setUserId(userId);
				payHistory.setMoney(totalFee);
				payHistory.setShopOrderNumber(orders.getShopOrderNumber());
				payHistory.setOrderNumber(orders.getOrderNumber());
				payHistory.setType(PayHistoryType.BUY.toIntValue());
				payHistory.setWay(createOrderVO.getPayWay());
				payHistoryDAO.insert(payHistory);

				// 插入交易记录
				TransactionAddVO transactionAddVO = new TransactionAddVO();
				BeanUtils.copyProperties(orders, transactionAddVO);
				transactionAddVO.setOrderId(orders.getId());
				transactionAddVO.setOrderType(orders.getType());
				transactionAddVO.setType(TransactionType.PAY.toIntValue());
				transactionAddVO.setNumber(number);
				transactionService.add(transactionAddVO);
				
				UserConfig userConfig = userConfigDAO.getUserConfig(userBO.getId());
				if(userConfig != null && StringUtils.isNoneBlank(userConfig.getId())){
					if(PayWay.CASH.toIntValue() == createOrderVO.getPayWay()){
						userConfig.setCurrentMoney(userConfig.getCurrentMoney() - totalFee);
					}else if(PayWay.REDEEM.toIntValue() == createOrderVO.getPayWay()){
						userConfig.setWithdrawalMoney(userConfig.getWithdrawalMoney() - totalFee);
					}
					userConfigDAO.update(userConfig);
				}
			}
			
			//消费赠送积分
			SystemConfig systemConfig = systemConfigDAO.find();
			if(systemConfig.getIsOpenConsume() == Is.YES.toIntValue()){
				UserConfig userConfig = userConfigDAO.getUserConfig(userBO.getId());
				Double sum = (totalFee * systemConfig.getConsumeValue() / 100);
				
				BigDecimal bg = new BigDecimal(userConfig.getLegeIntegral());
				BigDecimal bgSum = new BigDecimal(sum);
				bg = bg.add(bgSum).setScale(4, BigDecimal.ROUND_HALF_UP);
				if(sum > 0){
					userConfig.setPileLegeIntegral(bg.doubleValue());
					userConfig.setLegeIntegral(bg.doubleValue());
					userConfigDAO.update(userConfig);
				}
			}
		}else if(createOrderVO.getPayWay() == PayWay.WECHAT.toIntValue()){
			if (totalFee > 0) {
				// 发起微信支付申请
				OrderInfo orderInfo = new OrderInfo();
				orderInfo.setAttach(newOrder.getId());
				orderInfo.setOutTradeNo(orderNumber);
				orderInfo.setBody(WECHAT_BODY_KEY + "-" + orderNumber);
				orderInfo.setTotalFee(Math.round(totalFee * 100));
				orderInfo.setSpbillCreateIp(RequestUtil.getRealIp(request));
				orderInfo.setOpenId(userBO.getOpenId());
				orderInfo.setTradeType(createOrderVO.getTradeType());
				PayParam payParam = WeChatUtils.getPayParam(orderInfo);
				logger.error("form_id>>>>>>>>>>>>>>>>>>" + payParam.getFormId());
				if (StringUtils.isNoneBlank(payParam.getFormId())) {
					String key = DIYKey.getFormIdByOrderNumber(orderNumber);
					UserFormIdVO userFormIdVO = new UserFormIdVO();
					userFormIdVO.setUserId(userBO.getId());
					userFormIdVO.setFormId(payParam.getFormId());
					userFormIdVO.setEndTime(DateUtil.addDays(new Date(), 7));
					userCacheDAO.addHash(key, userFormIdVO);
				}
				map.put("patParam", payParam);
			} else {
				//如果支付金额小于0则不发起微信支付，直接更新掉订单状态。
				List<Orders> list = ordersDAO.getOrderByPay(userBO.getId(), orderNumber);
				for (Orders orders : list) {
					if (list.size() < 0)
						throw new OrderNotFoundException("Orders not found");

					couponsMoney += orders.getCouponsMoney();
					String userId = userBO.getId();
					orders.setPayTime(new Date());
					orders.setPayWay(PayWay.WECHAT.toIntValue());
					orders.setStatus(OrderStatus.PAID.toIntValue());
					ordersDAO.update(orders);
					
					//检查是否满足享有二级分润条件
					SystemConfig systemConfig = systemConfigDAO.find();
					if (systemConfig.getIsOpenMemberSell() == Is.YES.toIntValue()) {
						Double value = ordersDAO.sumPayMoney(userId);
						if (value >= systemConfig.getSellValue()) {
							User userParams = userDAO.query(userId);
							userParams.setIsMemberSell(Is.YES.toIntValue());
							userDAO.update(userParams);
						}
					}
					
					OrdersDataHistory ordersDataHistory = new OrdersDataHistory();
					ordersDataHistory.setOrdersId(orders.getId());
					ordersDataHistory.setShopId(orders.getShopId());
					ordersDataHistory.setOrderNumber(orders.getOrderNumber());
					ordersDataHistory.setShopOrderNumber(orders.getShopOrderNumber());
					ordersDataHistory.setRealMoney(orders.getRealMoney());
					ordersDataHistory.setPayMoney(totalPayMoney);
					ordersDataHistory.setFactPayMoney(orders.getPayMoney());
					//ordersDataHistory.setDeductionMoney(orders.getDeductionMoney());
					ordersDataHistory.setPostage(orders.getPostage());
					ordersDataHistory.setStatus(OrdersDataHistoryStatus.CLOSE.toIntValue());
					ordersDataHistory.setPayWay(PayWay.WECHAT.toIntValue());
					UserCoupons userCoupons = userCouponsDAO.getUserCoupons(userId,orders.getId(),orderNumber);
						if(userCoupons != null){
							ordersDataHistory.setCouponsId(orders.getUserCouponsId());
							ordersDataHistory.setCouponsType(userCoupons.getCouponsType());
							if(userCoupons.getCouponsType() == CouponsType.SHOP.toIntValue()){
								ordersDataHistory.setCouponsMoney(orders.getCouponsMoney());
							}else{
								Double avg = orders.getPayMoney() / totalFee * orders.getCouponsMoney();
								ordersDataHistory.setCouponsMoney(Format.decimal(avg));
							}
						}
					OrdersDataHistory ordersDataHistoryparams = ordersDataHistoryDAO.insert(ordersDataHistory);
					
					int number=0;
					List<OrdersGoods> ordersGoodsList = ordersGoodsDAO.getOrderGoodsByOrderId(orders.getId());
					for (OrdersGoods ordersGoods : ordersGoodsList) {

						number += ordersGoods.getNumber();
						//查询商品信息
						Goods goods = goodsDAO.query(ordersGoods.getGoodsId());
						//查询店铺信息
						Shop shop =  shopDAO.query(goods.getShopId());
						if (goods.getIsOpenSku() == Is.YES.toIntValue()) {
							SkuContent skuContent = skuContentDAO.query(ordersGoods.getSkuContentId());
							skuContent.setStock(skuContent.getStock() - ordersGoods.getNumber());// 库存
							skuContentDAO.update(skuContent);

							
							//添加待结算金额
							//Shop shop =  shopDAO.query(goods.getShopId());
							Double sumGoodsMoney = skuContent.getPrice() * ordersGoods.getNumber();
							Double waitSumMoney = sumGoodsMoney - (sumGoodsMoney * goods.getProfit() /100);
							if(goods.getIsOpenRebate() == Is.YES.toIntValue() && goods.getIsOpenSell() == Is.YES.toIntValue()){
								shop.setAccumulativeMoney(shop.getAccumulativeMoney()+waitSumMoney);
								shop.setMonthIncomeMoney(shop.getMonthIncomeMoney()+waitSumMoney);
								shop.setWithdrawalMoney(shop.getWithdrawalMoney()+waitSumMoney);
							}else{
								shop.setWaitSumMoney(shop.getWaitSumMoney()+waitSumMoney);
							}
							shopDAO.update(shop);
							
							OrdersDataHistory dataHistory = ordersDataHistoryDAO.query(ordersDataHistoryparams.getId());
							Industry industry = industryDAO.query(shop.getIndustryId());
							dataHistory.setShopMoney(dataHistory.getShopMoney()+waitSumMoney); 
							dataHistory.setProfitMoney(dataHistory.getProfitMoney() + (sumGoodsMoney - waitSumMoney));
							dataHistory.setIndustryFullName(industry.getName());
							ordersDataHistoryDAO.update(dataHistory);
							
							GoodsDataHistory goodsDataHistory = new GoodsDataHistory();
							goodsDataHistory.setGoodsId(goods.getId());
							goodsDataHistory.setShopId(goods.getShopId());
							goodsDataHistory.setOrdersDataHistoryId(ordersDataHistoryparams.getId());
							goodsDataHistory.setTypeId(goods.getTypeId());
							goodsDataHistory.setGoodsName(goods.getName());
							goodsDataHistory.setSkuContentName(skuContent.getStandards());
							goodsDataHistory.setNumber(ordersGoods.getNumber());
							goodsDataHistory.setPrice(ordersGoods.getPayMoney());
							goodsDataHistory.setIsOpenRebate(goods.getIsOpenRebate());
							goodsDataHistory.setProfit(goods.getProfit());
							goodsDataHistory.setShopMoney(waitSumMoney);
							goodsDataHistory.setProfitMoney(sumGoodsMoney - waitSumMoney);
							goodsDataHistory.setCouponsMoney(sumGoodsMoney / dataHistory.getPayMoney() * dataHistory.getCouponsMoney());
							GoodsDataHistory goodsDataHistoryParam = goodsDataHistoryDAO.insert(goodsDataHistory);
							
							//有SKU商品进入排队返利队列
							if(goods.getIsOpenRebate() == Is.YES.toIntValue()){
								for(int i = 0;i<ordersGoods.getNumber();i++){
									//检查是否进入队列
									OrdersGoods params = ordersGoodsDAO.query(ordersGoods.getId());
									if(params.getIsQueue() == Is.NO.toIntValue()){
										RebateVO rebateVO = new RebateVO();
										rebateVO.setGoodsId(goods.getId());
										rebateVO.setSkuContentId(skuContent.getId());
										rebateVO.setPrice(skuContent.getPrice());
										rebateVO.setShopId(goods.getShopId());
										rebateVO.setUserId(userId);
										rebateVO.setOrderId(ordersGoods.getOrderId());
										rebateVO.setGoodsName(goods.getName());
										rebateVO.setOrderGoodsId(ordersGoods.getId());
										RebateInfo rebateInfo = rebateService.addRebate(rebateVO);
										if (StringUtils.isNoneBlank(rebateInfo.getId())) {
											rebateService.updateRedate(rebateInfo);
										}
									}
									
								}
							}
							
							if(goods.getIsOpenSell() == Is.YES.toIntValue() && goods.getIsOpenRebate() == Is.YES.toIntValue()){
								//分销
								commissionHistoryService.add(userId, ordersGoods.getId(), userBO.getParentId(),ordersDataHistoryparams.getId(),goodsDataHistoryParam.getId());
							}
							
							goodsDataHistory = goodsDataHistoryDAO.query(goodsDataHistoryParam.getId());
							Double profit = (goodsDataHistory.getPrice()*goodsDataHistory.getNumber()) - goodsDataHistory.getShopMoney(); //利润
							//共分出多少钱
							Double sumMoney = goodsDataHistory.getReferrerMoney() +  goodsDataHistory.getPrimaryBenefitMoney()+goodsDataHistory.getSecondBenefitMoney()+goodsDataHistory.getShopGetBenefitMoney();
							Double grossMargin = profit - sumMoney; //毛利
							Double grossMarginRate = grossMargin / profit * 100;//毛利率
								if(!grossMarginRate.isNaN()){
									goodsDataHistory.setGrossMargin(grossMargin);
									goodsDataHistory.setGrossMarginRate(grossMarginRate);
								}
							goodsDataHistoryDAO.update(goodsDataHistory);
						}else{
							goods.setStock(goods.getStock() - ordersGoods.getNumber());//库存
							
							//添加待结算金额
							//Shop shop =  shopDAO.query(goods.getShopId());
							Double sumGoodsMoney = goods.getPrice() * ordersGoods.getNumber();
							Double waitSumMoney = sumGoodsMoney - (sumGoodsMoney * goods.getProfit() /100);
							if(goods.getIsOpenRebate() == Is.YES.toIntValue() && goods.getIsOpenSell() == Is.YES.toIntValue()){
								shop.setAccumulativeMoney(shop.getAccumulativeMoney()+waitSumMoney);
								shop.setMonthIncomeMoney(shop.getMonthIncomeMoney()+waitSumMoney);
								shop.setWithdrawalMoney(shop.getWithdrawalMoney()+waitSumMoney);
							}else{
								shop.setWaitSumMoney(shop.getWaitSumMoney()+waitSumMoney);
							}
							shopDAO.update(shop);
							
							
							OrdersDataHistory dataHistory = ordersDataHistoryDAO.query(ordersDataHistoryparams.getId());
							Industry industry = industryDAO.query(shop.getIndustryId());
							dataHistory.setShopMoney(dataHistory.getShopMoney()+waitSumMoney); 
							dataHistory.setProfitMoney(dataHistory.getProfitMoney() + (sumGoodsMoney - waitSumMoney));
							dataHistory.setIndustryFullName(industry.getName());
							ordersDataHistoryDAO.update(dataHistory);
							
							GoodsDataHistory goodsDataHistory = new GoodsDataHistory();
							goodsDataHistory.setGoodsId(goods.getId());
							goodsDataHistory.setShopId(goods.getShopId());
							goodsDataHistory.setOrdersDataHistoryId(ordersDataHistoryparams.getId());
							goodsDataHistory.setTypeId(goods.getTypeId());
							goodsDataHistory.setGoodsName(goods.getName());
							goodsDataHistory.setNumber(ordersGoods.getNumber());
							goodsDataHistory.setPrice(ordersGoods.getPayMoney());
							goodsDataHistory.setIsOpenRebate(goods.getIsOpenRebate());
							goodsDataHistory.setProfit(goods.getProfit());
							goodsDataHistory.setShopMoney(waitSumMoney);
							goodsDataHistory.setProfitMoney(sumGoodsMoney - waitSumMoney);
							goodsDataHistory.setCouponsMoney(sumGoodsMoney / dataHistory.getPayMoney() * dataHistory.getCouponsMoney());
							GoodsDataHistory goodsDataHistoryParam = goodsDataHistoryDAO.insert(goodsDataHistory);
							
							//没有SKU商品进入排队返利队列
							if(goods.getIsOpenRebate() == Is.YES.toIntValue()){
								for(int i = 0;i<ordersGoods.getNumber();i++){
									//检查是否进入队列
									OrdersGoods params = ordersGoodsDAO.query(ordersGoods.getId());
									if(params.getIsQueue() == Is.NO.toIntValue()){
										RebateVO rebateVO = new RebateVO();
										rebateVO.setGoodsId(goods.getId());
										rebateVO.setPrice(goods.getPrice());
										rebateVO.setShopId(goods.getShopId());
										rebateVO.setUserId(userId);
										rebateVO.setGoodsName(goods.getName());
										rebateVO.setOrderId(ordersGoods.getOrderId());
										rebateVO.setOrderGoodsId(ordersGoods.getId());
										RebateInfo rebateInfo = rebateService.addRebate(rebateVO);
										if (StringUtils.isNoneBlank(rebateInfo.getId())) {
											rebateService.updateRedate(rebateInfo);
										}
									}
								}
							}
							if(goods.getIsOpenSell() == Is.YES.toIntValue() && goods.getIsOpenRebate() == Is.YES.toIntValue()){
								//分销
								commissionHistoryService.add(userId, ordersGoods.getId(), userBO.getParentId(),ordersDataHistoryparams.getId(),goodsDataHistoryParam.getId());
							}
							goodsDataHistory = goodsDataHistoryDAO.query(goodsDataHistoryParam.getId());
							Double profit = (goodsDataHistory.getPrice()*goodsDataHistory.getNumber()) - goodsDataHistory.getShopMoney(); //利润
							//共分出多少钱
							Double sumMoney = goodsDataHistory.getReferrerMoney() +  goodsDataHistory.getPrimaryBenefitMoney()+goodsDataHistory.getSecondBenefitMoney()+goodsDataHistory.getShopGetBenefitMoney();
							Double grossMargin = profit - sumMoney; //毛利
							Double grossMarginRate = grossMargin / profit * 100;//毛利率
								if(!grossMarginRate.isNaN()){
									goodsDataHistory.setGrossMargin(grossMargin);
									goodsDataHistory.setGrossMarginRate(grossMarginRate);
								}
							goodsDataHistoryDAO.update(goodsDataHistory);
						}
						
						goods.setSalesVolume(goods.getSalesVolume()+ordersGoods.getNumber());//销量
						goodsDAO.update(goods);

						// 生成购买记录
						UserGoods userGoods = new UserGoods();
						userGoods.setShopId(orders.getShopId());
						userGoods.setGoodsId(ordersGoods.getGoodsId());
						userGoods.setUserId(userBO.getId());
						userGoods.setType(UserGoodsType.BUY.toIntValue());
						userGoods.setNumber(ordersGoods.getNumber());
						userGoodsDAO.insert(userGoods);
						
						//统计订单数据表毛利
						OrdersDataHistory newOrdersDataHistory =  ordersDataHistoryDAO.query(ordersDataHistoryparams.getId());
						if(newOrdersDataHistory != null){
							Double profit = newOrdersDataHistory.getPayMoney()- newOrdersDataHistory.getPostage() - newOrdersDataHistory.getShopMoney();
							Double sumMoney = newOrdersDataHistory.getShareBenefitMoney() + newOrdersDataHistory.getReferrerMoney()+newOrdersDataHistory.getAgencyBenefit() + newOrdersDataHistory.getAgencyAccount();
							Double grossMargin = profit - sumMoney; //毛利
							Double grossMarginRate = grossMargin / profit * 100;//毛利率
								if(!grossMarginRate.isNaN()){
									newOrdersDataHistory.setGrossMargin(grossMargin);
									newOrdersDataHistory.setGrossMarginRate(grossMarginRate);
								}
							ordersDataHistoryDAO.update(newOrdersDataHistory);
						}
						
						if(goods.getIsOpenSell() == Is.YES.toIntValue() && goods.getIsOpenRebate() == Is.YES.toIntValue()){
							//城市代理数据对接
							Double profitsMoney = ordersGoods.getPayMoney()  * ordersGoods.getProfit() / 100;
							Map<String, Object> contentMap = new HashMap<>();
							contentMap.put("id", ordersGoods.getId());
							contentMap.put("ps", profitsMoney);
							contentMap.put("areaId", shop.getAreaCountyId());
							contentMap.put("payAmount", ordersGoods.getPayMoney());
							contentMap.put("shopOrderNumber", orders.getShopOrderNumber());
							contentMap.put("shopId", shop.getId());
							contentMap.put("shopName", shop.getName());
							String content = JSONUtil.toJsonStr(contentMap);
							rabbitMQService.sendToStoreBusiness(ordersGoods.getId(), content);
						}
					}
					//添加交易记录
					PayHistory payHistory = new PayHistory();
					payHistory.setShopId(orders.getShopId());
					payHistory.setUserId(userId);
					payHistory.setMoney(totalFee);
					payHistory.setShopOrderNumber(orders.getShopOrderNumber());
					payHistory.setOrderNumber(orders.getOrderNumber());
					payHistory.setType(PayHistoryType.BUY.toIntValue());
					payHistory.setWay(createOrderVO.getPayWay());
					payHistoryDAO.insert(payHistory);

					// 插入交易记录
					TransactionAddVO transactionAddVO = new TransactionAddVO();
					BeanUtils.copyProperties(orders, transactionAddVO);
					transactionAddVO.setOrderId(orders.getId());
					transactionAddVO.setOrderType(orders.getType());
					transactionAddVO.setType(TransactionType.PAY.toIntValue());
					transactionAddVO.setNumber(number);
					transactionService.add(transactionAddVO);
					
					/*UserConfig userConfig = userConfigDAO.getUserConfig(userBO.getId());
					if(userConfig != null && StringUtils.isNoneBlank(userConfig.getId())){
						userConfig.setCurrentMoney(userConfig.getCurrentMoney() - totalFee);
						userConfigDAO.update(userConfig);
					}*/
				}
				map.put("patParam", null);
				totalFee = 0.0;
			}
		}
		
		// 更新优惠劵信息
		if (couponsMap.size() > 0) {
			userCouponsService.handleUserCoupons(couponsMap);
		} else {
			if (StringUtils.isNoneBlank(createOrderVO.getInternalDiscountId())) {
				userCouponsService.handleUserCoupons(newOrder.getOrderNumber(), createOrderVO.getInternalDiscountId());
			}
		}
		map.put("payMoney", totalFee);
		result.setData(map);
		return result;
	}


	public ResultVO createQRCode(String userId, String orderNumber) {
		ResultVO result = new ResultVO();
		List<Orders> list = ordersDAO.getOrderByPay(userId, orderNumber);
		if (list.size() < 0) {
			throw new OrdersNotFoundException("Order not found");
		}
		for (Orders orders : list) {
			String qrcodeName = orders.getId() + "." + FileUtil.QR_CODE_FORMAT;
			String fullpath = dataQrcodePath + qrcodeName;
			File file = new File(fullpath);
			if (file.exists())
				FileUtil.removeFile(fullpath);
			String qrCodeNumber = OrderNumberUtils.getOrderQrCodeNumber();
			FileUtil.createQRCode(qrCodeNumber, fullpath);
			try {
				AliyunOSSClientUtil.uploadObject2OSS(new FileInputStream(new File(dataQrcodePath+qrcodeName)) , qrcodeName, backetName, qrcodePath);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}
			
			orders.setQrCode(qrcodeName);
			orders.setValidationCode(qrCodeNumber);
			orders.setStatus(OrderStatus.WAITUSE.toIntValue());
			ordersDAO.update(orders);

			// 检查是否满足享有二级分润条件
			SystemConfig systemConfig = systemConfigDAO.find();
			if (systemConfig.getIsOpenMemberSell() == Is.YES.toIntValue()) {
				Double value = ordersDAO.sumPayMoney(userId);
				if (value >= systemConfig.getSellValue()) {
					User userParams = userDAO.query(userId);
					userParams.setIsMemberSell(Is.YES.toIntValue());
					userDAO.update(userParams);
				}
			}
		}

		return result;
	}

	@Override
	public int orderTotalCount(String userId) {
		return ordersDAO.orderTotalCount(userId);
	}

	// 微信支付成功后
	@Transactional
	public String getWechatNotify(String xml) {
		try {
			Map<String, String> msgObj = MessageUtil.parseXml(xml);
			String openId = msgObj.get("openid");
			String timeEnd = msgObj.get("time_end");
			String transactionNumber = msgObj.get("transaction_id");
			String totalFee = msgObj.get("total_fee");
			String orderNumber = msgObj.get("out_trade_no");
			String attach = msgObj.get("attach");
			
			/*String openId = "ostSJ5Q3wrIo9hu5Nn1eGtj63v6E";
			String timeEnd = "2018-08-19 16:06:00";
			String transactionNumber = "4200100122101817216850971476";
			String totalFee = "1000";
			String orderNumber = "6754334338335386";
			String attach = "e2a6c933042c43bfb752f39651bec46e";	*/
			
			
			User user = userDAO.checkOpenId(openId);
			Double payMoney = 0.0;
			Double couponsMoney = 0.0;
			if (StringUtils.isNotBlank(totalFee))
				payMoney = Double.valueOf(totalFee);
			payMoney = payMoney / 100;
			
			if (attach.equals(Constants.WECHAT_ATTACH_FOR_LOGISTICS)) {
				if (user == null || StringUtils.isBlank(user.getId()))
					throw new UserNotFoundException("User not found");

			} else if (attach.equals(Constants.WECHAT_ATTACH_FOR_RECHARGE)) {
				
				RechargeRecord rechargeRecord = rechargeRecordDAO.findByNumber(orderNumber);

				UserConfig userConfig = userConfigDAO.getUserConfig(user.getId());

				Double balance = userConfig.getCurrentMoney();
				balance = balance + rechargeRecord.getRechargeMoney();
				if (rechargeRecord.getGiveType() == RechargeConfigureGiveType.MONEY.toIntType()) {
					balance = balance + rechargeRecord.getGiveValue();
					
					RechargeRecord giveValueRechargeRecord = new RechargeRecord();
					giveValueRechargeRecord.setUserId(user.getId());
					giveValueRechargeRecord.setOrderNumber(rechargeRecord.getOrderNumber());
					giveValueRechargeRecord.setRechargeMoney(rechargeRecord.getGiveValue());
					giveValueRechargeRecord.setPayWay(PayWay.OTHER.toIntValue());
					//赠送方式
					giveValueRechargeRecord.setGiveType(RechargeConfigureGiveType.MONEY.toIntType());
					//赠送金额
					giveValueRechargeRecord.setGiveValue(0.0);
					giveValueRechargeRecord.setStatus(RechargeRecordStatus.ALREADY_PAID.toIntValue());
					rechargeRecordDAO.insert(giveValueRechargeRecord);
				}
				balance = Format.decimal(balance);
				userConfig.setCurrentMoney(balance);
				rechargeRecord.setStatus(RechargeRecordStatus.ALREADY_PAID.toIntValue());
				rechargeRecord.setTransactionNumber(transactionNumber);
				rechargeRecordDAO.update(rechargeRecord);
				userConfigDAO.update(userConfig);

				/*
				 * Recharge recharge = rechargeDAO.getRecharge(member.getId(),
				 * orderNumber); if(recharge != null &&
				 * StringUtils.isNotBlank(recharge.getId())){ MemberConfig
				 * memberConfig =
				 * memberConfigDAO.getMemberConfig(member.getId());
				 * if(memberConfig!=null &&
				 * StringUtils.isNotBlank(memberConfig.getId())){ //更新用户金额
				 * memberConfig.setCurrentMoney(memberConfig.getCurrentMoney()+
				 * recharge.getMoney());
				 * memberConfig.setPileMoney(memberConfig.getPileMoney()+
				 * recharge.getMoney()); memberConfigDAO.update(memberConfig); }
				 * } //更新充值记录 recharge.setMoney(recharge.getMoney());
				 * recharge.setPayMoney(recharge.getPayMoney());
				 * recharge.setStatus(RechargeStatus.SUCCEED.toIntStatus());
				 * rechargeDAO.update(recharge);
				 */

			}else if (attach.equals(Constants.WECHAT_ATTACH_FOR_MEMBER_CARD)) {
				//购买会员卡
//				Date now = new Date();
//				UserMemberCard  userMemberCard  = userMemberCardDAO.query(orderNumber);
//				userMemberCard.setState(MemberCardStatus.NORMAL.toIntStatus());
//				
//				if (userMemberCard.getIsPresentCoupon() == Is.YES.toIntValue()) {
//					if (userMemberCard.getCouponsId() != null) {
//						couponsService.insert(userMemberCard.getUserId(), userMemberCard.getCouponsId());
//					}
//				}
//				ShopClient shopClient = shopClientDAO.findClientByUserId(userMemberCard.getUserId(),userMemberCard.getShopId());
//				if (shopClient == null) {
//					shopClient = new ShopClient();
//					shopClient.setUserId(userMemberCard.getUserId());
//					shopClient.setMemberCardId(userMemberCard.getMemberCardId());
//					shopClient.setGrade(MemberLevelCode.ZERO.toIntValue());
//					shopClient.setClientStatus(ShopClientStatus.MEMBER.toIntStatus());
//					shopClient.setClientDate(now);
//					shopClient.setMemberDate(now);
//					shopClient.setMemberEndDate(userMemberCard.getEndTime());
//					shopClientDAO.insert(shopClient);
//				} else {
//					shopClient.setMemberDate(now);
//					shopClient.setMemberEndDate(userMemberCard.getEndTime());
//					shopClient.setGrade(userMemberCard.getCardGrade());
//					shopClientDAO.update(shopClient);
//				}
//				
//				userMemberCardDAO.update(userMemberCard);
			}else if (attach.equals(Constants.WECHAT_ATTACH_FOR_SHIASD)) {
				//商家入驻回调
				ShopsLocated shopsLocated = shopsLocatedDAO.byNumber(orderNumber);
				if (shopsLocated == null){
					throw new NotFoundException("ShopsLocated not found");
				}
				shopsLocated.setIsPay(Is.YES.toIntValue());
				shopsLocated.setPayTime(new Date());
				shopsLocated.setTransactionNumber(transactionNumber);
				shopsLocatedDAO.update(shopsLocated);
				
			}else if (attach.equals(Constants.WECHAT_ATTACH_FOR_BALANCE_HISTORY)) {
				//会员卡储值
				BalanceHistory balanceHistory = balanceHistoryDAO.getByOrderNumber(orderNumber);
				
				// 在商户会员表中修改记录
				ShopClient shopClient = shopClientDAO.findClientByUserId(balanceHistory.getUserId(),balanceHistory.getCsId());
				
				Double balance = shopClient.getBalance();
				
				balance += balanceHistory.getBalanceChange();
				
				if(balanceHistory.getCouponsId()!=null){
					couponsService.insert(balanceHistory.getUserId(), balanceHistory.getCouponsId());
				}
				
				if(balanceHistory.getGiveIntegral()!=null){
					Integer nowIntegral = shopClient.getNowIntegral();
					
					nowIntegral += balanceHistory.getGiveIntegral();
					
					shopClient.setNowIntegral(nowIntegral);
				}

				if(balanceHistory.getGiveMoney()!=null){
					balance += balanceHistory.getGiveMoney();
					
					BalanceHistory giveMoneyBalanceHistory = new BalanceHistory();
					giveMoneyBalanceHistory.setTransactionNumber(orderNumber);
					giveMoneyBalanceHistory.setClientId(shopClient.getId());
					giveMoneyBalanceHistory.setCsId(balanceHistory.getCsId());
					giveMoneyBalanceHistory.setUserId(balanceHistory.getUserId());
					
					giveMoneyBalanceHistory.setOperation(BalanceHistoryOperation.STORAGE_VALUE.toIntValue());
					giveMoneyBalanceHistory.setStatus(BalanceHistoryStatus.ALREADY_PAID.toIntValue());
					giveMoneyBalanceHistory.setBalanceChange(balanceHistory.getGiveMoney());
					
					balanceHistoryDAO.insert(giveMoneyBalanceHistory);
				}
				
				shopClient.setBalance(balance);
				
				balanceHistory.setStatus(BalanceHistoryStatus.ALREADY_PAID.toIntValue());
				balanceHistory.setTransactionNumber(transactionNumber);
				shopClientDAO.update(shopClient);
				
				balanceHistoryDAO.update(balanceHistory);
				
			}else if (attach.equals(Constants.WECHAT_ATTACH_FOR_MEMBER)) {
				/*
				 * MemberSign memberSign =
				 * memberSignDAO.findByMemberId(member.getId());
				 * if(memberSign!=null &&
				 * StringUtils.isNotBlank(memberSign.getId())){
				 * memberSign.setStatus(MemberSignStatus.PASS.toIntValue());
				 * memberSignDAO.update(memberSign);
				 * 
				 * if(StringUtils.isNotBlank(memberSign.getIdentity())){
				 * member.setIdentity(memberSign.getIdentity()); }
				 * member.setName(memberSign.getName());
				 * if(StringUtils.isBlank(member.getMobilePhone())){
				 * member.setMobilePhone(memberSign.getMobilePhone()); }
				 * 
				 * member.setStatus(MemberStatus.ACTIVE.toIntValue());
				 * memberDAO.update(member);
				 * 
				 * MemberConfig memberConfig =
				 * memberConfigDAO.getMemberConfig(member.getId());
				 * if(StringUtils.isNotBlank(memberConfig.getId())){
				 * memberConfig.setLevel(MemberLevelCode.STAIR.toIntValue());
				 * memberConfigDAO.update(memberConfig); } }
				 */
			} else if (attach.equals(Constants.WECHAT_ATTACH_FOR_VIP)) {
				UserVip userVip = userVipDAO.checkVipByNumber(orderNumber);
				if (userVip == null) {
					throw new UserVipNotFoundException("User vip not found");
				}
				//检查是否有使用的VIP
				UserVip vip = userVipDAO.checkUserVip(user.getId());
				if(vip != null){
					vip.setIsUse(IsUse.NO.toIntValue());
					userVipDAO.update(vip);
				}
				
				userVip.setType(UserVipType.BUY.toIntType());
				userVip.setIsUse(Is.YES.toIntValue());
				userVipDAO.update(userVip);

				// 添加身份历史
				VipHistory vipHistory = new VipHistory();
				vipHistory.setUserId(user.getId());
				vipHistory.setVipId(userVip.getVipId());
				vipHistory.setTransactionNumber(transactionNumber);
				vipHistory.setPayMoney(payMoney);
				vipHistory.setPayTime(new Date());
				vipHistory.setPayWay(PayWay.WECHAT.toIntValue());
				vipHistory.setStatus(VipHistoryStatus.PAID.toIntStatus());
				vipHistory.setPresentIntegral(payMoney);
				vipHistoryDAO.insert(vipHistory);

				// 更新余额
				UserConfig userConfig = userConfigDAO.getUserConfig(user.getId());
				userConfig.setPileMoney(userConfig.getPileMoney() + payMoney);
				userConfig.setCurrentMoney(userConfig.getCurrentMoney() + payMoney);
				userConfigDAO.update(userConfig);

			} else if (attach.equals(Constants.WECHAT_ATTACH_FOR_SHOP_ORDER_NUMBER)) {
				if (user == null || StringUtils.isBlank(user.getId()))
					throw new UserNotFoundException("User not found");

				Orders orders = ordersDAO.findByShopOrderNumber(user.getId(), orderNumber);
				if (orders == null)
					throw new OrderNotFoundException("Orders not found");

				String userId = user.getId();
				orders.setTransactionNumber(transactionNumber);
				orders.setPayTime(DateUtil.parseDate(DateUtil.DATETIME_PATTERN_SECOND_SHORT, timeEnd));
				orders.setPayWay(PayWay.WECHAT.toIntValue());
				orders.setStatus(OrderStatus.PAID.toIntValue());
				ordersDAO.update(orders);

			/*	UserConfig userConfig = userConfigDAO.getUserConfig(userId);
				if(userConfig != null && StringUtils.isNoneBlank(userConfig.getId())){
					userConfig.setCurrentMoney(userConfig.getWithdrawalMoney() - orders.getDeductionMoney());
					userConfigDAO.update(userConfig);
				}*/
				
				// 检查是否满足享有二级分润条件
				SystemConfig systemConfig = systemConfigDAO.find();
				if (systemConfig.getIsOpenMemberSell() == Is.YES.toIntValue()) {
					Double value = ordersDAO.sumPayMoney(userId);
					if (value >= systemConfig.getSellValue()) {
						User userParams = userDAO.query(userId);
						userParams.setIsMemberSell(Is.YES.toIntValue());
						userDAO.update(userParams);
					}
					
					//财务报表及资产管理
					OrdersDataHistory ordersDataHistory = new OrdersDataHistory();
					ordersDataHistory.setOrdersId(orders.getId());
					ordersDataHistory.setShopId(orders.getShopId());
					ordersDataHistory.setOrderNumber(orders.getOrderNumber());
					ordersDataHistory.setShopOrderNumber(orders.getShopOrderNumber());
					ordersDataHistory.setRealMoney(orders.getRealMoney());
					ordersDataHistory.setTransactionNumber(orders.getTransactionNumber());
					ordersDataHistory.setPayMoney(orders.getPayMoney());
					ordersDataHistory.setFactPayMoney(orders.getPayMoney());
					//ordersDataHistory.setDeductionMoney(orders.getDeductionMoney());
					ordersDataHistory.setPostage(orders.getPostage());
					ordersDataHistory.setStatus(OrdersDataHistoryStatus.CLOSE.toIntValue());
					
					UserCoupons userCoupons = userCouponsDAO.getUserCoupons(userId,orders.getId(),orderNumber);
						if(userCoupons != null){
							ordersDataHistory.setCouponsId(orders.getUserCouponsId());
							ordersDataHistory.setCouponsType(userCoupons.getCouponsType());
						if(userCoupons.getCouponsType() == CouponsType.SHOP.toIntValue()){
							ordersDataHistory.setCouponsMoney(orders.getCouponsMoney());
						}else{
							Double avg = orders.getPayMoney() / payMoney * orders.getCouponsMoney();
							ordersDataHistory.setCouponsMoney(Format.decimal(avg));
						}
					}
					OrdersDataHistory ordersDataHistoryparams = ordersDataHistoryDAO.insert(ordersDataHistory);
					
					int number=0;
					List<OrdersGoods> ordersGoodsList = ordersGoodsDAO.getOrderGoodsByOrderId(orders.getId());
					for (OrdersGoods ordersGoods : ordersGoodsList){
						couponsMoney += orders.getCouponsMoney();
						number+=ordersGoods.getNumber();
						Goods goods = goodsDAO.query(ordersGoods.getGoodsId());
						Shop shop =  shopDAO.query(orders.getShopId());
						if(goods.getIsOpenSku() == Is.YES.toIntValue()){
							SkuContent skuContent = skuContentDAO.query(ordersGoods.getSkuContentId());
							skuContent.setStock(skuContent.getStock() - ordersGoods.getNumber());//库存
							skuContentDAO.update(skuContent);
							//添加待结算金额
							Double sumGoodsMoney = skuContent.getPrice() * number;
							Double waitSumMoney = sumGoodsMoney - (sumGoodsMoney * goods.getProfit() /100);
							if(goods.getIsOpenRebate() == Is.YES.toIntValue() && goods.getIsOpenSell() == Is.YES.toIntValue()){
								shop.setAccumulativeMoney(shop.getAccumulativeMoney()+waitSumMoney);
								shop.setMonthIncomeMoney(shop.getMonthIncomeMoney()+waitSumMoney);
								shop.setWithdrawalMoney(shop.getWithdrawalMoney()+waitSumMoney);
							}else{
								shop.setWaitSumMoney(shop.getWaitSumMoney()+waitSumMoney);
							}
							shopDAO.update(shop);
							
							OrdersDataHistory dataHistory = ordersDataHistoryDAO.query(ordersDataHistoryparams.getId());
							Industry industry = industryDAO.query(shop.getIndustryId());
							dataHistory.setShopMoney(dataHistory.getShopMoney()+waitSumMoney); 
							dataHistory.setProfitMoney(dataHistory.getProfitMoney() + (sumGoodsMoney - waitSumMoney));
							dataHistory.setIndustryFullName(industry.getName());
							ordersDataHistoryDAO.update(dataHistory);
							
							GoodsDataHistory goodsDataHistory = new GoodsDataHistory();
							goodsDataHistory.setGoodsId(goods.getId());
							goodsDataHistory.setShopId(goods.getShopId());
							goodsDataHistory.setOrdersDataHistoryId(ordersDataHistoryparams.getId());
							goodsDataHistory.setTypeId(goods.getTypeId());
							goodsDataHistory.setGoodsName(goods.getName());
							goodsDataHistory.setSkuContentName(skuContent.getStandards());
							goodsDataHistory.setNumber(number);
							goodsDataHistory.setPrice(ordersGoods.getPayMoney());
							goodsDataHistory.setIsOpenRebate(goods.getIsOpenRebate());
							goodsDataHistory.setProfit(goods.getProfit());
							goodsDataHistory.setShopMoney(waitSumMoney);
							goodsDataHistory.setProfitMoney(sumGoodsMoney - waitSumMoney);
							goodsDataHistory.setCouponsMoney(sumGoodsMoney / orders.getPayMoney() * dataHistory.getCouponsMoney());
							GoodsDataHistory goodsDataHistoryParam = goodsDataHistoryDAO.insert(goodsDataHistory);
							
							//有SKU商品进入排队返利队列
							if(goods.getIsOpenRebate() == Is.YES.toIntValue()){
								for(int i = 0;i<ordersGoods.getNumber();i++){
									//检查是否进入队列
									OrdersGoods params = ordersGoodsDAO.query(ordersGoods.getId());
									if(params.getIsQueue() == Is.NO.toIntValue()){
										RebateVO rebateVO = new RebateVO();
										rebateVO.setGoodsId(goods.getId());
										rebateVO.setSkuContentId(skuContent.getId());
										rebateVO.setPrice(skuContent.getPrice());
										rebateVO.setShopId(goods.getShopId());
										rebateVO.setGoodsName(goods.getName());
										rebateVO.setUserId(userId);
										rebateVO.setOrderId(ordersGoods.getOrderId());
										rebateVO.setOrderGoodsId(ordersGoods.getId());
										RebateInfo rebateInfo = rebateService.addRebate(rebateVO);
										if(StringUtils.isNoneBlank(rebateInfo.getId())){
											rebateService.updateRedate(rebateInfo);
										}
									}
								}
							}
							
							if(goods.getIsOpenSell() == Is.YES.toIntValue() && goods.getIsOpenRebate() == Is.YES.toIntValue()){
								//分销
								commissionHistoryService.add(userId, ordersGoods.getId(), user.getParentId(),ordersDataHistoryparams.getId(),goodsDataHistoryParam.getId());
							}
							goodsDataHistory = goodsDataHistoryDAO.query(goodsDataHistoryParam.getId());
							Double profit = (goodsDataHistory.getPrice()*goodsDataHistory.getNumber()) - goodsDataHistory.getShopMoney(); //利润
							//共分出多少钱
							Double sumMoney = goodsDataHistory.getReferrerMoney() +  goodsDataHistory.getPrimaryBenefitMoney()+goodsDataHistory.getSecondBenefitMoney()+goodsDataHistory.getShopGetBenefitMoney();
							Double grossMargin = profit - sumMoney; //毛利
							Double grossMarginRate = grossMargin / profit * 100;//毛利率
								if(!grossMarginRate.isNaN()){
									goodsDataHistory.setGrossMargin(grossMargin);
									goodsDataHistory.setGrossMarginRate(grossMarginRate);
								}
							goodsDataHistoryDAO.update(goodsDataHistory);
							
						}else{
							goods.setStock(goods.getStock() - ordersGoods.getNumber());//库存
							
							//添加待结算金额
							//Shop shop =  shopDAO.query(orders.getShopId());
							Double sumGoodsMoney = goods.getPrice() * number;
							Double waitSumMoney = sumGoodsMoney - (sumGoodsMoney * goods.getProfit() /100);
							if(goods.getIsOpenRebate() == Is.YES.toIntValue()){
								shop.setAccumulativeMoney(shop.getAccumulativeMoney()+waitSumMoney);
								shop.setMonthIncomeMoney(shop.getMonthIncomeMoney()+waitSumMoney);
								shop.setWithdrawalMoney(shop.getWithdrawalMoney()+waitSumMoney);
							}else{
								shop.setWaitSumMoney(shop.getWaitSumMoney()+waitSumMoney);
							}
							shopDAO.update(shop);
							
							OrdersDataHistory dataHistory = ordersDataHistoryDAO.query(ordersDataHistoryparams.getId());
							Industry industry = industryDAO.query(shop.getIndustryId());
							dataHistory.setShopMoney(dataHistory.getShopMoney()+waitSumMoney); 
							dataHistory.setProfitMoney(dataHistory.getProfitMoney() + (sumGoodsMoney - waitSumMoney));
							dataHistory.setIndustryFullName(industry.getName());
							ordersDataHistoryDAO.update(dataHistory);
							
							GoodsDataHistory goodsDataHistory = new GoodsDataHistory();
							goodsDataHistory.setGoodsId(goods.getId());
							goodsDataHistory.setShopId(goods.getShopId());
							goodsDataHistory.setOrdersDataHistoryId(ordersDataHistoryparams.getId());
							goodsDataHistory.setTypeId(goods.getTypeId());
							goodsDataHistory.setGoodsName(goods.getName());
							goodsDataHistory.setNumber(number);
							goodsDataHistory.setPrice(ordersGoods.getPayMoney());
							goodsDataHistory.setIsOpenRebate(goods.getIsOpenRebate());
							goodsDataHistory.setProfit(goods.getProfit());
							goodsDataHistory.setShopMoney(waitSumMoney);
							goodsDataHistory.setProfitMoney(sumGoodsMoney - waitSumMoney);
							goodsDataHistory.setCouponsMoney(sumGoodsMoney / orders.getPayMoney() * dataHistory.getCouponsMoney());
							GoodsDataHistory goodsDataHistoryParam = goodsDataHistoryDAO.insert(goodsDataHistory);
							
							//没有SKU商品进入排队返利队列
							if(goods.getIsOpenRebate() == Is.YES.toIntValue()){
								for(int i = 0;i<ordersGoods.getNumber();i++){
									//检查是否进入队列
									OrdersGoods params = ordersGoodsDAO.query(ordersGoods.getId());
									if(params.getIsQueue() == Is.NO.toIntValue()){
										RebateVO rebateVO = new RebateVO();
										rebateVO.setGoodsId(goods.getId());
										rebateVO.setPrice(goods.getPrice());
										rebateVO.setShopId(goods.getShopId());
										rebateVO.setGoodsName(goods.getName());
										rebateVO.setUserId(userId);
										rebateVO.setOrderId(ordersGoods.getOrderId());
										rebateVO.setOrderGoodsId(ordersGoods.getId());
										RebateInfo rebateInfo = rebateService.addRebate(rebateVO);
										if(StringUtils.isNoneBlank(rebateInfo.getId())){
											rebateService.updateRedate(rebateInfo);
										}
									}
									
								}
							}
							if(goods.getIsOpenSell() == Is.YES.toIntValue() && goods.getIsOpenRebate() == Is.YES.toIntValue()){
								commissionHistoryService.add(userId, ordersGoods.getId(), user.getParentId(),ordersDataHistoryparams.getId(),goodsDataHistoryParam.getId());
							}
							
							goodsDataHistory = goodsDataHistoryDAO.query(goodsDataHistoryParam.getId());
							Double profit = (goodsDataHistory.getPrice()*goodsDataHistory.getNumber()) - goodsDataHistory.getShopMoney(); //利润
							//共分出多少钱
							Double sumMoney = goodsDataHistory.getReferrerMoney() +  goodsDataHistory.getPrimaryBenefitMoney()+goodsDataHistory.getSecondBenefitMoney()+goodsDataHistory.getShopGetBenefitMoney();
							Double grossMargin = profit - sumMoney; //毛利
							Double grossMarginRate = grossMargin / profit * 100;//毛利率
								if(!grossMarginRate.isNaN()){
									goodsDataHistory.setGrossMargin(grossMargin);
									goodsDataHistory.setGrossMarginRate(grossMarginRate);
								}
							goodsDataHistoryDAO.update(goodsDataHistory);
						}
						goods.setSalesVolume(goods.getSalesVolume() + ordersGoods.getNumber());// 销量
						goodsDAO.update(goods);
						
						// 生成购买记录
						UserGoods userGoods = new UserGoods();
						userGoods.setShopId(orders.getShopId());
						userGoods.setGoodsId(ordersGoods.getGoodsId());
						userGoods.setUserId(user.getId());
						userGoods.setType(UserGoodsType.BUY.toIntValue());
						userGoods.setNumber(ordersGoods.getNumber());
						userGoodsDAO.insert(userGoods);
						
						OrdersDataHistory newOrdersDataHistory =  ordersDataHistoryDAO.query(ordersDataHistoryparams.getId());
						if(newOrdersDataHistory != null){
							Double profit = newOrdersDataHistory.getPayMoney()- newOrdersDataHistory.getPostage() - newOrdersDataHistory.getShopMoney();
							Double sumMoney = newOrdersDataHistory.getShareBenefitMoney() + newOrdersDataHistory.getReferrerMoney()+newOrdersDataHistory.getAgencyBenefit() + newOrdersDataHistory.getAgencyAccount();
							Double grossMargin = profit - sumMoney; //毛利
							Double grossMarginRate = grossMargin / profit * 100;//毛利率
							if(!grossMarginRate.isNaN()){
								newOrdersDataHistory.setGrossMargin(grossMargin);
								newOrdersDataHistory.setGrossMarginRate(grossMarginRate);
							}
							ordersDataHistoryDAO.update(newOrdersDataHistory);
						}
						
						if(goods.getIsOpenSell() == Is.YES.toIntValue() && goods.getIsOpenRebate() == Is.YES.toIntValue()){
							//调用城市代理,传输数据
							Double profitsMoney = ordersGoods.getPayMoney() * ordersGoods.getNumber() * ordersGoods.getProfit() / 100;
							Map<String, Object> map = new HashMap<>();
							map.put("id", ordersGoods.getId());
							map.put("ps", profitsMoney);
							map.put("areaId", shop.getAreaCountyId());
							map.put("payAmount", ordersGoods.getPayMoney());
							map.put("shopOrderNumber", orders.getShopOrderNumber());
							map.put("shopId", shop.getId());
							map.put("shopName", shop.getName());
							String content = JSONUtil.toJsonStr(map);
							rabbitMQService.sendToStoreBusiness(ordersGoods.getId(), content);
						}
					}
						
					//添加交易记录
					PayHistory payHistory = new PayHistory();
					payHistory.setShopId(orders.getShopId());
					payHistory.setUserId(userId);
					payHistory.setMoney(payMoney);
					payHistory.setShopOrderNumber(orders.getShopOrderNumber());
					payHistory.setOrderNumber(orders.getOrderNumber());
					payHistory.setType(PayHistoryType.BUY.toIntValue());
					payHistory.setWay(PayWay.WECHAT.toIntValue());
					payHistoryDAO.insert(payHistory);

					// 插入交易记录
					TransactionAddVO transactionAddVO = new TransactionAddVO();
					BeanUtils.copyProperties(orders, transactionAddVO);
					transactionAddVO.setOrderId(orders.getId());
					transactionAddVO.setOrderType(orders.getType());
					transactionAddVO.setType(TransactionType.PAY.toIntValue());
					transactionAddVO.setNumber(number);
					transactionService.add(transactionAddVO);
				}
			} else {
				if (user == null || StringUtils.isBlank(user.getId()))
					throw new UserNotFoundException("User not found");

				List<Orders> list = ordersDAO.getOrderByPay(user.getId(), orderNumber);
				for (Orders orders : list) {
					if (list.size() < 0)
						throw new OrderNotFoundException("Orders not found");

					couponsMoney += orders.getCouponsMoney();
					String userId = user.getId();
					Orders order = new Orders();
					order.setId(orders.getId());
					order.setTransactionNumber(transactionNumber);
					order.setPayTime(DateUtil.parseDate(DateUtil.DATETIME_PATTERN_SECOND_SHORT, timeEnd));
					order.setPayWay(PayWay.WECHAT.toIntValue());
					order.setStatus(OrderStatus.PAID.toIntValue());
					ordersDAO.update(order); 
					

				/*	UserConfig userConfig = userConfigDAO.getUserConfig(userId);
					if(userConfig != null && StringUtils.isNoneBlank(userConfig.getId())){
						userConfig.setCurrentMoney(userConfig.getWithdrawalMoney() - orders.getDeductionMoney());
						userConfigDAO.update(userConfig);
					}*/
					
					//检查是否满足享有二级分润条件
					SystemConfig systemConfig = systemConfigDAO.find();
					if (systemConfig.getIsOpenMemberSell() == Is.YES.toIntValue()) {
						Double value = ordersDAO.sumPayMoney(userId);
						if (value >= systemConfig.getSellValue()) {
							User userParams = userDAO.query(userId);
							userParams.setIsMemberSell(Is.YES.toIntValue());
							userDAO.update(userParams);
						}
					}
					
					OrdersDataHistory ordersDataHistory = new OrdersDataHistory();
					ordersDataHistory.setOrdersId(orders.getId());
					ordersDataHistory.setShopId(orders.getShopId());
					ordersDataHistory.setOrderNumber(orders.getOrderNumber());
					ordersDataHistory.setShopOrderNumber(orders.getShopOrderNumber());
					ordersDataHistory.setRealMoney(orders.getRealMoney());
					ordersDataHistory.setTransactionNumber(orders.getTransactionNumber());
					ordersDataHistory.setPayMoney(orders.getPayMoney());
					ordersDataHistory.setPostage(orders.getPostage());
					ordersDataHistory.setStatus(OrdersDataHistoryStatus.CLOSE.toIntValue());
					UserCoupons userCoupons = userCouponsDAO.getUserCoupons(userId,orders.getId(),orderNumber);
						if(userCoupons != null){
							ordersDataHistory.setCouponsId(orders.getUserCouponsId());
							ordersDataHistory.setCouponsType(userCoupons.getCouponsType());
							if(userCoupons.getCouponsType() == CouponsType.SHOP.toIntValue()){
								ordersDataHistory.setCouponsMoney(orders.getCouponsMoney());
							}else{
								Double avg = orders.getPayMoney() / payMoney * orders.getCouponsMoney();
								ordersDataHistory.setCouponsMoney(Format.decimal(avg));
							}
						}
					OrdersDataHistory ordersDataHistoryparams = ordersDataHistoryDAO.insert(ordersDataHistory);
					
					int number=0;
					List<OrdersGoods> ordersGoodsList = ordersGoodsDAO.getOrderGoodsByOrderId(orders.getId());
					for (OrdersGoods ordersGoods : ordersGoodsList) {

						number += ordersGoods.getNumber();
						Goods goods = goodsDAO.query(ordersGoods.getGoodsId());
						//查询店铺信息
						Shop shop =  shopDAO.query(goods.getShopId());
						if (goods.getIsOpenSku() == Is.YES.toIntValue()) {
							SkuContent skuContent = skuContentDAO.query(ordersGoods.getSkuContentId());
							skuContent.setStock(skuContent.getStock() - ordersGoods.getNumber());// 库存
							skuContentDAO.update(skuContent);

							//添加待结算金额
							Double sumGoodsMoney = skuContent.getPrice() * ordersGoods.getNumber();
							Double waitSumMoney = sumGoodsMoney - (sumGoodsMoney * goods.getProfit() /100);
							if(goods.getIsOpenRebate() == Is.YES.toIntValue() && goods.getIsOpenSell() == Is.YES.toIntValue()){
								shop.setAccumulativeMoney(shop.getAccumulativeMoney()+waitSumMoney);
								shop.setMonthIncomeMoney(shop.getMonthIncomeMoney()+waitSumMoney);
								shop.setWithdrawalMoney(shop.getWithdrawalMoney()+waitSumMoney);
							}else{
								shop.setWaitSumMoney(shop.getWaitSumMoney()+waitSumMoney);
							}
							shopDAO.update(shop);
							
							OrdersDataHistory dataHistory = ordersDataHistoryDAO.query(ordersDataHistoryparams.getId());
							Industry industry = industryDAO.query(shop.getIndustryId());
							dataHistory.setShopMoney(dataHistory.getShopMoney()+waitSumMoney); 
							dataHistory.setProfitMoney(dataHistory.getProfitMoney() + (sumGoodsMoney - waitSumMoney));
							dataHistory.setIndustryFullName(industry.getName());
							ordersDataHistoryDAO.update(dataHistory);
							
							GoodsDataHistory goodsDataHistory = new GoodsDataHistory();
							goodsDataHistory.setGoodsId(goods.getId());
							goodsDataHistory.setShopId(goods.getShopId());
							goodsDataHistory.setOrdersDataHistoryId(ordersDataHistoryparams.getId());
							goodsDataHistory.setTypeId(goods.getTypeId());
							goodsDataHistory.setGoodsName(goods.getName());
							goodsDataHistory.setSkuContentName(skuContent.getStandards());
							goodsDataHistory.setNumber(ordersGoods.getNumber());
							goodsDataHistory.setPrice(ordersGoods.getPayMoney());
							goodsDataHistory.setIsOpenRebate(goods.getIsOpenRebate());
							goodsDataHistory.setProfit(goods.getProfit());
							goodsDataHistory.setShopMoney(waitSumMoney);
							goodsDataHistory.setProfitMoney(sumGoodsMoney - waitSumMoney);
							goodsDataHistory.setCouponsMoney(sumGoodsMoney / orders.getPayMoney() * dataHistory.getCouponsMoney());
							GoodsDataHistory goodsDataHistoryParam = goodsDataHistoryDAO.insert(goodsDataHistory);
							
							//有SKU商品进入排队返利队列
							if(goods.getIsOpenRebate() == Is.YES.toIntValue()){
								for(int i = 0;i<ordersGoods.getNumber();i++){
									//检查是否进入队列
									OrdersGoods params = ordersGoodsDAO.query(ordersGoods.getId());
									if(params.getIsQueue() == Is.NO.toIntValue()){
										RebateVO rebateVO = new RebateVO();
										rebateVO.setGoodsId(goods.getId());
										rebateVO.setSkuContentId(skuContent.getId());
										rebateVO.setPrice(skuContent.getPrice());
										rebateVO.setShopId(goods.getShopId());
										rebateVO.setUserId(userId);
										rebateVO.setOrderId(ordersGoods.getOrderId());
										rebateVO.setGoodsName(goods.getName());
										rebateVO.setOrderGoodsId(ordersGoods.getId());
										RebateInfo rebateInfo = rebateService.addRebate(rebateVO);
										if (StringUtils.isNoneBlank(rebateInfo.getId())) {
											rebateService.updateRedate(rebateInfo);
										}
									}
									
								}
							}
							
							if(goods.getIsOpenSell() == Is.YES.toIntValue() && goods.getIsOpenRebate() == Is.YES.toIntValue()){
								//分销
								commissionHistoryService.add(userId, ordersGoods.getId(), user.getParentId(),ordersDataHistoryparams.getId(),goodsDataHistoryParam.getId());
							}
							
							goodsDataHistory = goodsDataHistoryDAO.query(goodsDataHistoryParam.getId());
							Double profit = (goodsDataHistory.getPrice()*goodsDataHistory.getNumber()) - goodsDataHistory.getShopMoney(); //利润
							//共分出多少钱
							Double sumMoney = goodsDataHistory.getReferrerMoney() +  goodsDataHistory.getPrimaryBenefitMoney()+goodsDataHistory.getSecondBenefitMoney()+goodsDataHistory.getShopGetBenefitMoney();
							Double grossMargin = profit - sumMoney; //毛利
							Double grossMarginRate = grossMargin / profit * 100;//毛利率
								if(!grossMarginRate.isNaN()){
									goodsDataHistory.setGrossMargin(grossMargin);
									goodsDataHistory.setGrossMarginRate(grossMarginRate);
								}
							goodsDataHistoryDAO.update(goodsDataHistory);
						}else{
							goods.setStock(goods.getStock() - ordersGoods.getNumber());//库存
							
							//添加待结算金额
							//Shop shop =  shopDAO.query(goods.getShopId());
							Double sumGoodsMoney = goods.getPrice() * ordersGoods.getNumber();
							Double waitSumMoney = sumGoodsMoney - (sumGoodsMoney * goods.getProfit() /100);
							if(goods.getIsOpenRebate() == Is.YES.toIntValue() && goods.getIsOpenSell() == Is.YES.toIntValue()){
								shop.setAccumulativeMoney(shop.getAccumulativeMoney()+waitSumMoney);
								shop.setMonthIncomeMoney(shop.getMonthIncomeMoney()+waitSumMoney);
								shop.setWithdrawalMoney(shop.getWithdrawalMoney()+waitSumMoney);
							}else{
								shop.setWaitSumMoney(shop.getWaitSumMoney()+waitSumMoney);
							}
							shopDAO.update(shop);
							
							
							OrdersDataHistory dataHistory = ordersDataHistoryDAO.query(ordersDataHistoryparams.getId());
							Industry industry = industryDAO.query(shop.getIndustryId());
							dataHistory.setShopMoney(dataHistory.getShopMoney()+waitSumMoney); 
							dataHistory.setProfitMoney(dataHistory.getProfitMoney() + (sumGoodsMoney - waitSumMoney));
							dataHistory.setIndustryFullName(industry.getName());
							ordersDataHistoryDAO.update(dataHistory);
							
							GoodsDataHistory goodsDataHistory = new GoodsDataHistory();
							goodsDataHistory.setGoodsId(goods.getId());
							goodsDataHistory.setShopId(goods.getShopId());
							goodsDataHistory.setOrdersDataHistoryId(ordersDataHistoryparams.getId());
							goodsDataHistory.setTypeId(goods.getTypeId());
							goodsDataHistory.setGoodsName(goods.getName());
							goodsDataHistory.setNumber(ordersGoods.getNumber());
							goodsDataHistory.setPrice(ordersGoods.getPayMoney());
							goodsDataHistory.setIsOpenRebate(goods.getIsOpenRebate());
							goodsDataHistory.setProfit(goods.getProfit());
							goodsDataHistory.setShopMoney(waitSumMoney);
							goodsDataHistory.setProfitMoney(sumGoodsMoney - waitSumMoney);
							goodsDataHistory.setCouponsMoney(sumGoodsMoney / orders.getPayMoney() * dataHistory.getCouponsMoney());
							GoodsDataHistory goodsDataHistoryParam = goodsDataHistoryDAO.insert(goodsDataHistory);
							
							//没有SKU商品进入排队返利队列
							if(goods.getIsOpenRebate() == Is.YES.toIntValue()){
								for(int i = 0;i<ordersGoods.getNumber();i++){
									//检查是否进入队列
									OrdersGoods params = ordersGoodsDAO.query(ordersGoods.getId());
									if(params.getIsQueue() == Is.NO.toIntValue()){
										RebateVO rebateVO = new RebateVO();
										rebateVO.setGoodsId(goods.getId());
										rebateVO.setPrice(goods.getPrice());
										rebateVO.setShopId(goods.getShopId());
										rebateVO.setUserId(userId);
										rebateVO.setGoodsName(goods.getName());
										rebateVO.setOrderId(ordersGoods.getOrderId());
										rebateVO.setOrderGoodsId(ordersGoods.getId());
										RebateInfo rebateInfo = rebateService.addRebate(rebateVO);
										if (StringUtils.isNoneBlank(rebateInfo.getId())) {
											rebateService.updateRedate(rebateInfo);
										}
									}
								}
							}
							if(goods.getIsOpenSell() == Is.YES.toIntValue() && goods.getIsOpenRebate() == Is.YES.toIntValue()){
								//分销
								commissionHistoryService.add(userId, ordersGoods.getId(), user.getParentId(),ordersDataHistoryparams.getId(),goodsDataHistoryParam.getId());
							}
							
							goodsDataHistory = goodsDataHistoryDAO.query(goodsDataHistoryParam.getId());
							Double profit = (goodsDataHistory.getPrice()*goodsDataHistory.getNumber()) - goodsDataHistory.getShopMoney(); //利润
							//共分出多少钱
							Double sumMoney = goodsDataHistory.getReferrerMoney() +  goodsDataHistory.getPrimaryBenefitMoney()+goodsDataHistory.getSecondBenefitMoney()+goodsDataHistory.getShopGetBenefitMoney();
							Double grossMargin = profit - sumMoney; //毛利
							Double grossMarginRate = grossMargin / profit * 100;//毛利率
								if(!grossMarginRate.isNaN()){
									goodsDataHistory.setGrossMargin(grossMargin);
									goodsDataHistory.setGrossMarginRate(grossMarginRate);
								}
							goodsDataHistoryDAO.update(goodsDataHistory);
						}
						
						goods.setSalesVolume(goods.getSalesVolume()+ordersGoods.getNumber());//销量
						goodsDAO.update(goods);

						// 生成购买记录
						UserGoods userGoods = new UserGoods();
						userGoods.setShopId(orders.getShopId());
						userGoods.setGoodsId(ordersGoods.getGoodsId());
						userGoods.setUserId(user.getId());
						userGoods.setType(UserGoodsType.BUY.toIntValue());
						userGoods.setNumber(ordersGoods.getNumber());
						userGoodsDAO.insert(userGoods);
						
						//统计订单数据表毛利
						OrdersDataHistory newOrdersDataHistory =  ordersDataHistoryDAO.query(ordersDataHistoryparams.getId());
						if(newOrdersDataHistory != null){
							Double profit = newOrdersDataHistory.getPayMoney()- newOrdersDataHistory.getPostage() - newOrdersDataHistory.getShopMoney();
							Double sumMoney = newOrdersDataHistory.getShareBenefitMoney() + newOrdersDataHistory.getReferrerMoney()+newOrdersDataHistory.getAgencyBenefit() + newOrdersDataHistory.getAgencyAccount();
							Double grossMargin = profit - sumMoney; //毛利
							Double grossMarginRate = grossMargin / profit * 100;//毛利率
								if(!grossMarginRate.isNaN()){
									newOrdersDataHistory.setGrossMargin(grossMargin);
									newOrdersDataHistory.setGrossMarginRate(grossMarginRate);
								}
							ordersDataHistoryDAO.update(newOrdersDataHistory);
						}
						
						//城市代理数据对接
						if(goods.getIsOpenSell() == Is.YES.toIntValue() && goods.getIsOpenRebate() == Is.YES.toIntValue()){
							Double profitsMoney = ordersGoods.getPayMoney() * ordersGoods.getProfit() / 100;
							Map<String, Object> map = new HashMap<>();
							map.put("id", ordersGoods.getId());
							map.put("ps", profitsMoney);
							map.put("areaId", shop.getAreaCountyId());
							map.put("payAmount", ordersGoods.getPayMoney());
							map.put("shopOrderNumber", orders.getShopOrderNumber());
							map.put("shopId", shop.getId());
							map.put("shopName", shop.getName());
							String content = JSONUtil.toJsonStr(map);
							rabbitMQService.sendToStoreBusiness(ordersGoods.getId(), content);
						}
					}

					
					//添加交易记录
					PayHistory payHistory = new PayHistory();
					payHistory.setShopId(orders.getShopId());
					payHistory.setUserId(userId);
					payHistory.setMoney(payMoney);
					payHistory.setShopOrderNumber(orders.getShopOrderNumber());
					payHistory.setOrderNumber(orders.getOrderNumber());
					payHistory.setType(PayHistoryType.BUY.toIntValue());
					payHistory.setWay(PayWay.WECHAT.toIntValue());
					payHistoryDAO.insert(payHistory);

					// 插入交易记录
					TransactionAddVO transactionAddVO = new TransactionAddVO();
					BeanUtils.copyProperties(orders, transactionAddVO);
					transactionAddVO.setOrderId(orders.getId());
					transactionAddVO.setOrderType(orders.getType());
					transactionAddVO.setType(TransactionType.PAY.toIntValue());
					transactionAddVO.setNumber(number);
					transactionService.add(transactionAddVO);
				}
			}
			SortedMap<Object, Object> parameters = new TreeMap<Object, Object>();
			parameters.put("return_code", "SUCCESS");
			parameters.put("return_msg", "OK");
			String resultXML = WeChatUtils.getRequestXml(parameters);
			
			//消费赠送乐积分
			SystemConfig systemConfig = systemConfigDAO.find();
			if(systemConfig.getIsOpenConsume() == Is.YES.toIntValue()){
				UserConfig userConfig = userConfigDAO.getUserConfig(user.getId());
				Double sum = (payMoney * systemConfig.getConsumeValue() / 100);
				
				BigDecimal bg = new BigDecimal(userConfig.getLegeIntegral());
				BigDecimal bgSum = new BigDecimal(sum);
				bg = bg.add(bgSum).setScale(4, BigDecimal.ROUND_HALF_UP);
				if(sum > 0){
					userConfig.setPileLegeIntegral(bg.doubleValue());
					userConfig.setLegeIntegral(bg.doubleValue());
					userConfigDAO.update(userConfig);
				}
			}
			
			//发送消息模板
			String key = DIYKey.getFormIdByOrderNumber(orderNumber);
			UserFormIdVO formIdVO = userCacheDAO.getHash(key, UserFormIdVO.class);
			if(formIdVO != null){
				Map<String, Object> data = TemplateMessageUtil.getMessageData(new String[]{transactionNumber,orderNumber,payMoney.toString(),
						couponsMoney.toString(),DateUtil.format(new Date()),"400-931-8788","如有疑问,请联系客服"});
				TemplateMessageParam tmp = new TemplateMessageParam();
				tmp.setTouser(openId);
				tmp.setTemplateId(TemplateMessageUtil.BUY_SUCCESS);//模板ID
				tmp.setFormId(formIdVO.getFormId());
				tmp.setEmphasisKeyword("keyword3.DATA");
				tmp.setData(data);//内容
				TemplateMessageUtil.pullMessage(tmp);	
			}
			return resultXML;
		} catch (Exception e) {
			logger.error("pay retrun error:", e);
			SortedMap<Object, Object> parameters = new TreeMap<Object, Object>();
			parameters.put("return_code", "FAIL");
			parameters.put("return_msg", "NO");
			String resultXML = WeChatUtils.getRequestXml(parameters);
			return resultXML;
		}

	}

	@Override
	public String refundNotify(String xml) {
		String content = null;
		try {
			logger.info("Refund Notify : " + xml);
			Map<String, String> msgObj = MessageUtil.parseXml(xml);
			String returnCode = msgObj.get("return_code");
			if(returnCode.equals("SUCCESS")){
				String reqInfo = msgObj.get("req_info");
				String secret = WeChatUtils.getSecret();
				String key = Coder.encodeByMD5(secret).toLowerCase();
				logger.info("reqInfo: " + reqInfo + ",secret: " + secret + ",key: " + key);
				content = AESUtil.decryptFor256(reqInfo, key);
				logger.info(content);
			}else{
				// 退款失败
				logger.info("------- Refund Fail --------");
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		return content;
	}
	
	@Override
	public ResultVO wechatPay(HttpServletRequest request, String userId, String ordersId, String tradeType) {
		ResultVO result = new ResultVO();
		UserBO userBO = userDAO.findUserId(userId);
		if (userBO == null || StringUtils.isBlank(userBO.getId()))
			throw new UserNotFoundException("User not found");

		Orders orders = ordersDAO.query(ordersId);
		if (orders == null || StringUtils.isBlank(orders.getId())) {
			result.setStatus(APICodeStatus.ORDER_NOT_FOUND);
			result.setMessage("Orders not found.");
			return result;
		}

		// 发起微信支付申请
		// String body = messageService.getMessage(WECHAT_BODY_KEY, new
		// String[]{orderNumber}, Lang.ZH_CN.toStringValue());

		OrderInfo orderInfo = new OrderInfo();
		orderInfo.setAttach(Constants.WECHAT_ATTACH_FOR_SHOP_ORDER_NUMBER);
		orderInfo.setOutTradeNo(orders.getShopOrderNumber());
		orderInfo.setBody(WECHAT_BODY_KEY + "-" + orders.getShopOrderNumber());
		orderInfo.setTotalFee(Math.round(orders.getPayMoney() * 100));
		orderInfo.setSpbillCreateIp(RequestUtil.getRealIp(request));
		orderInfo.setOpenId(userBO.getOpenId());
		orderInfo.setTradeType(tradeType);
		PayParam payParam = WeChatUtils.getPayParam(orderInfo);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("shopOrderNumber", orders.getShopOrderNumber());
		map.put("orderNumber", orders.getOrderNumber());
		map.put("orderId", orders.getId());
		map.put("patParam", payParam);
		result.setData(map);
		return result;
	}

	@Override
	public ResultVO wechatPaySuccess(String shopOrderNumber) {
		ResultVO result = new ResultVO();
		Orders orders = ordersDAO.getOrderByShopOrderNumber(shopOrderNumber);
		result.setData(orders);
		return result;
	}

	@Override
	public ResultVO logisticsTrace(String ordersId) {
		ResultVO result = new ResultVO();
		OrdersBO ordersBO = ordersDAO.findLogistics(ordersId);
		if (ordersBO == null || StringUtils.isBlank(ordersBO.getLogisticsNumber())) {
			throw new OrdersNotFoundException("找不到订单");
		}
		Map<String, Object> map = new HashMap<String, Object>();
		LogisticsResultDate logisticsResultDate = LogisticsUtil.expressQuery(ordersBO.getLogisticsNumber(),null);
		if (logisticsResultDate == null) {
			throw new LogisticsNumberErrorException("未查询到该物流信息");
		}
		map.put("logisticsResultDate", logisticsResultDate.getResult());
		map.put("logisticsNumber", ordersBO.getLogisticsNumber());
		map.put("logisticsName", ordersBO.getLogisticsName());
		result.setData(map);
		return result;
	}

	@Override
	@Transactional
	public ResultVO editStatusByShopOrderNumber(String shopOrderNumber, Integer status) {
		ResultVO result = new ResultVO();
		try {
			// 修改状态
			Orders orders = ordersDAO.getOrderByShopOrderNumber(shopOrderNumber);
			orders.setStatus(status);
			orders.setConfirmTime(DateUtil.getCurrentDate());
			orders.setConfirmType(ConfirmType.USER.toIntValue());
			ordersDAO.update(orders);

			// 更新店铺资产
			/*OrdersBO params = ordersDAO.findOrderById(orders.getId());
			if (orders != null && StringUtils.isNoneBlank(orders.getShopId())) {
				Double money = params.getPayMoney() - (params.getPayMoney() * params.getProfit() / 100);
				Shop shop = shopDAO.query(orders.getShopId());
				shop.setWithdrawalMoney(shop.getWithdrawalMoney() + money);
				shop.setAccumulativeMoney(shop.getAccumulativeMoney() + money);
				shop.setMonthIncomeMoney(shop.getMonthIncomeMoney() + money);
				if ((shop.getWaitSumMoney() - money) >= 0) {
					shop.setWaitSumMoney(shop.getWaitSumMoney() - money);
				}
				shopDAO.update(shop);
			}*/
		} catch (Exception e) {
			e.printStackTrace();
			result.setStatus(APICodeStatus.ORDER_UPDATE_STATUS_IS_FAIL);
			result.setMessage("update orders status fail" + shopOrderNumber);
		}
		return result;
	}

	@Override
	@Transactional
	public ResultVO delOrders(String orderNumber) {
		ResultVO result = new ResultVO();

		String ordersGoodsId = ordersGoodsDAO.getOrderGoodsByOrderNumber(orderNumber);
		if (StringUtils.isNotBlank(ordersGoodsId)) {
			// ordersGoodsDAO.delete(ordersGoodsId);
			ordersGoodsDAO.updateToDelete(ordersGoodsId);
		}

		Orders orders = ordersDAO.getOrdersByOrderNumber(orderNumber);
		if (orders != null) {
			// ordersDAO.delete(orders);
			ordersDAO.updateToDelete(orders.getId());
		}
		return result;
	}

	@Override
	public ResultVO resetPayHistory() {
		ResultVO result = new ResultVO();
		List<Orders> list = ordersDAO.getOrderByStatus();
		for (Orders orders : list) {
			// 添加交易记录
			PayHistory payHistory = new PayHistory();
			payHistory.setShopId(orders.getShopId());
			payHistory.setUserId(orders.getUserId());
			payHistory.setMoney(orders.getPayMoney());
			payHistory.setShopOrderNumber(orders.getShopOrderNumber());
			payHistory.setOrderNumber(orders.getOrderNumber());
			payHistory.setType(PayHistoryType.BUY.toIntValue());
			payHistory.setWay(PayWay.WECHAT.toIntValue());
			payHistory.setCreatedTime(orders.getCreatedTime());
			payHistoryDAO.insert(payHistory);
		}
		return result;
	}

	@Override
	public ResultVO findAppletsOrderInfo(String userId,String areaCode, List<String> carts) {
		ResultVO result = new ResultVO();
		//店铺商品集合
		Map<String,Map<GoodsBO,Integer>> goodsMap = new HashMap<String,Map<GoodsBO,Integer>>();
		// 1.按照购物车ID数组查询所有的商品以及对应的店铺(分类好)
		Set<ShopDetailBO> shopSet = new HashSet<ShopDetailBO>();
		String cart = "";
		for (String s : carts) {
			cart += "'" + s + "',";
		}
		List<String> shopIdList = new ArrayList<String>();
		
		cart = cart.substring(0, cart.length() - 1);
		List<CartBO> cartList = cartDAO.getCartExtendInfoById(cart);
		Double total = new Double(0);
		if (cartList != null && cartList.size() > 0) {
			for (CartBO bo : cartList) {
				ShopDetailBO shopBo = new ShopDetailBO();
				shopBo.setShopId(bo.getShopId());
				shopBo.setShopName(bo.getShopName());
				shopBo.setShopLogo(bo.getShopHeadImgUrl());
				shopSet.add(shopBo);
			}
			for (ShopDetailBO sbo : shopSet) {
				shopIdList.add(sbo.getShopId());
				
				Map<GoodsBO,Integer> attributeMap = null;
				if(goodsMap.containsKey(sbo.getShopId())){
					attributeMap = goodsMap.get(sbo.getShopId());
				}else{
					attributeMap = new HashMap<GoodsBO,Integer>();
					goodsMap.put(sbo.getShopId(), attributeMap);
				}
				
				Double realMoney = new Double(0);
//				Double postage = new Double(0);
				List<GoodsDetailBO> list = new ArrayList<GoodsDetailBO>();
				for (CartBO bo : cartList) {
					if (bo.getShopId().equals(sbo.getShopId())) {
						GoodsDetailBO goodsBo = new GoodsDetailBO();
						BeanUtils.copyProperties(bo, goodsBo);
						goodsBo.setId(bo.getGoodsId());
						goodsBo.setName(bo.getGoodsName());
						
						//将GoodsDetailBO 转换成 GoodsBO 对象 并添加到 attributeMap 中
						postageTemplateService.transformation(attributeMap, goodsBo);
						
						if (goodsBo.getPrice() != null) {
							realMoney += goodsBo.getPrice() * goodsBo.getNumber();
							total += realMoney;
						}
//						if (!goodsBo.getPostagePrice().equals(new Double(0))) {
//							postage += goodsBo.getPostagePrice();
//						}
						list.add(goodsBo);
					}
				}
//				sbo.setPostage(postage);
				sbo.setRealMoney(realMoney);
				sbo.setGoods(list);
			}
			FreightVO  freightVO = postageTemplateService.freight(userId,areaCode,goodsMap);
			for (ShopDetailBO sbo : shopSet) {
				sbo.setPostage(freightVO.getFreightMap().get(sbo.getShopId()));
				for(GoodsDetailBO gbo:sbo.getGoods()){
					if(freightVO.getNoSupportGoodsIds().indexOf(gbo.getId())>=0){
						gbo.setNoSupport(false);
					}
				}
			}
		}
		
		// 2.优惠劵信息查询，当前用户在当前商家中可用的优惠劵以及总部的优惠劵
		List<Shop> shoList = shopDAO.getShop(shopIdList.iterator());
		StringBuffer findInShopSet = new StringBuffer();
		StringBuffer findInChainIdSet = new StringBuffer();
		for(Shop s:shoList){
			if(s.getIsChain()!=null){
				if(s.getIsChain() == Is.YES.toIntValue()){
					findInChainIdSet.append(s.getChainId()+",");
				}
			}
			findInShopSet.append(s.getId()+",");
		}
		if(findInShopSet.length()>1){
			findInShopSet.deleteCharAt(findInShopSet.length()-1);
		}
		if(findInChainIdSet.length()>1){
			findInChainIdSet.deleteCharAt(findInChainIdSet.length()-1);
		}
		
		List<UserCouponsInfoBO> couponsList = userCouponsDAO.getCouponsByUserIdAndShopId(userId, findInShopSet.toString(),findInChainIdSet.toString());
		coupons: for (int i = 0; i < couponsList.size(); i++) {
			UserCouponsInfoBO ucBO = couponsList.get(i);
			if (ucBO.getThreshold().equals(CouponFullSubtraction.UNRESTRICTED.toIntValue())) {
				continue;
			}
			if (ucBO.getPlatform().equals(CouponsPlatform.INTERNAL.toIntValue())) {
				if (ucBO.getFullPriceReduction() > total) {
					couponsList.remove(ucBO);
					continue;
				}
			}else{
				for (ShopDetailBO sbo : shopSet) {
					if (ucBO.getShopId().equals(sbo.getShopId())) {
						if (ucBO.getThreshold().equals(CouponFullSubtraction.FULL_SUBTRACTION.toIntValue())) {
							if (ucBO.getFullPriceReduction() > sbo.getRealMoney()) {
								couponsList.remove(ucBO);
								continue coupons;
							}
						}
					}
				}
			}
		}
		List<CouponsDetailsVO> list =  couponsService.formatCoupons(couponsList);
		// 3.将地址信息查询出来(默认)
		Address address = addressDAO.getDefalutAddress(userId);
		// 4.运费按照商品中的运费累计
		// 5.将用户配置信息查询出来(包含现金分等)
		UserConfigVO userConfigVO = new UserConfigVO();
		UserConfig userConfig = userConfigDAO.getUserConfig(userId);
		BeanUtils.copyProperties(userConfig,userConfigVO);
		Map<String, Object> map = new HashMap<String, Object>();
		
		map.put("shop", shopSet);
		map.put("coupons", list);
		map.put("address", address);
		map.put("userConfig", userConfigVO);
		result.setData(map);
		return result;
	}

}
